<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>地图热点展示</title>
<!-- Prism.js CSS for syntax highlighting -->
<link href="css/prism-tomorrow.min.css" rel="stylesheet">
<!-- Marked.js for Markdown parsing -->
<script src="js/marked.min.js"></script>
<!-- 临时禁用Prism.js以避免错误 -->
<!--
<script src="js/prism-core.min.js"></script>
<script>
// 确保 Prism 对象存在后再加载其他组件
if (typeof Prism !== 'undefined') {
    // 添加基本的语言支持
    Prism.languages.javascript = Prism.languages.extend('clike', {
        'class-name': [
            Prism.languages.clike['class-name'],
            {
                pattern: /(^|[^$\w\xA0-\uFFFF])[A-Z]\w*(?=\.(?:prototype|constructor))/,
                lookbehind: true
            }
        ],
        'keyword': [
            {
                pattern: /((?:^|})\s*)(?:catch|finally)\b/,
                lookbehind: true
            },
            {
                pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|(?:get|set)(?=\s*[\[$\w\xA0-\uFFFF])|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
                lookbehind: true
            }
        ],
        'function': /#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
        'number': /\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,
        'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
    });
}
</script>
-->
<!-- 样式定义 -->
<style>
body {
    margin: 0;
    padding: 70px 20px 60px 20px; /* 顶部70px为导航栏，底部60px为任务栏 */
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    text-align: center;
}

.container {
    max-width: 1500px;
    margin: 0 auto;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

h1 {
    color: #333;
    margin-bottom: 10px;
}

p {
    color: #666;
    margin-bottom: 20px;
}

.image-container {
    margin: 20px 0;
    position: relative;
    display: inline-block;
}

/* 热点可视化层 */
.hotspot-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 10;
}

.hotspot-area {
    position: absolute;
    background: rgba(0, 123, 255, 0.3);
    border: 2px solid rgba(0, 123, 255, 0.8);
    border-radius: 4px;
    cursor: pointer;
    pointer-events: auto;
    transition: background-color 0.3s ease;
    z-index: 20;
}

.hotspot-area:hover {
    background: rgba(0, 123, 255, 0.5);
    border-color: rgba(0, 123, 255, 1);
}

/* 工具提示样式 */
.tooltip {
    display: none;
    position: fixed;
    background: rgba(0, 0, 0, 0.95);
    color: white;
    padding: 12px 16px;
    border-radius: 8px;
    font-size: 14px;
    z-index: 9999;
    pointer-events: none;
    white-space: pre-wrap;
    max-width: 300px;
    line-height: 1.5;
    box-shadow: 0 6px 20px rgba(0,0,0,0.5);
    border: 2px solid rgba(255,255,255,0.2);
    backdrop-filter: blur(4px);
}

.tooltip::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -8px;
    border-width: 8px;
    border-style: solid;
    border-color: rgba(0, 0, 0, 0.95) transparent transparent transparent;
}

/* 弹窗样式 */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 10000;
    backdrop-filter: blur(2px);
}

.modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #2b2b2b; /* 类似Sublime Text的深色背景 */
    padding: 0;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    max-width: 90%;
    max-height: 90%;
    overflow: hidden;
    color: #f8f8f2; /* 浅色文字 */
    display: flex;
    flex-direction: column;
    min-width: 800px;
    min-height: 600px;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: #333;
    border-bottom: 1px solid #555;
}

.modal-title {
    font-size: 18px;
    font-weight: bold;
    color: #f8f8f2;
    margin: 0;
}

.close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #f8f8f2;
    padding: 5px;
    border-radius: 3px;
    transition: background-color 0.3s;
}

.close-btn:hover {
    background: #555;
    color: #fff;
}

.modal-body {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* 编辑器容器 - 标签页样式 */
.editor-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    flex: 1;
}

/* 标签页头部 */
.tab-headers {
    display: flex;
    background: #3c3c3c;
    border-bottom: 1px solid #555;
    margin: 0;
    padding: 0;
}

.tab-header {
    flex: 1;
    padding: 12px 20px;
    background: #3c3c3c;
    color: #f8f8f2;
    border: none;
    border-right: 1px solid #555;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    transition: all 0.2s ease;
    position: relative;
}

.tab-header:last-child {
    border-right: none;
}

.tab-header:hover {
    background: #4c4c4c;
}

.tab-header.active {
    background: #a6e22e;
    color: #272822;
}

.tab-header.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: #272822;
}

/* 标签页内容区域 */
.tab-content {
    flex: 1;
    position: relative;
    overflow: hidden;
    min-height: 500px; /* 确保有最小高度 */
}

.tab-pane {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: none;
    overflow: auto;
    padding: 10px;
    background: #2b2b2b; /* 给一个背景色便于调试 */
}

.tab-pane.active {
    display: block !important;
}

/* 移除原有的分屏样式 */
.editor-pane {
    display: none;
}

.pane-header {
    display: none;
}

.editor-content {
    flex: 1;
    position: relative;
    overflow: auto;
}

/* Markdown编辑器样式 */
.markdown-editor {
    width: 100% !important;
    height: 500px !important; /* 设置固定高度而不是100% */
    min-height: 400px !important; /* 最小高度 */
    background: #272822 !important; /* Sublime Text Monokai背景色 */
    color: #f8f8f2 !important;
    border: 1px solid #444 !important;
    padding: 20px !important;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
    font-size: 14px !important;
    line-height: 1.5 !important;
    resize: vertical !important; /* 允许垂直调整大小 */
    outline: none !important;
    tab-size: 4 !important;
    box-sizing: border-box !important; /* 确保padding不会溢出 */
    display: block !important;
    opacity: 1 !important;
    visibility: visible !important;
}

.markdown-editor::placeholder {
    color: #75715e;
}

/* 预览区域样式 */
.preview-content {
    padding: 20px;
    height: 100%;
    overflow-y: auto;
    background: #2b2b2b;
    color: #f8f8f2;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    line-height: 1.6;
}

/* Markdown预览样式 */
.preview-content h1, .preview-content h2, .preview-content h3, 
.preview-content h4, .preview-content h5, .preview-content h6 {
    color: #f92672;
    margin-top: 1.5em;
    margin-bottom: 0.5em;
}

.preview-content p {
    margin-bottom: 1em;
}

.preview-content pre {
    background: #272822;
    border: 1px solid #555;
    border-radius: 4px;
    overflow-x: auto;
    margin: 1em 0;
}

.preview-content code {
    background: #3e3d32;
    color: #e6db74;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

.preview-content pre code {
    background: none;
    padding: 0;
}

.preview-content blockquote {
    border-left: 4px solid #66d9ef;
    padding-left: 1em;
    margin-left: 0;
    color: #75715e;
}

.preview-content table {
    border-collapse: collapse;
    width: 100%;
    margin: 1em 0;
}

.preview-content th, .preview-content td {
    border: 1px solid #555;
    padding: 8px 12px;
    text-align: left;
}

.preview-content th {
    background: #3c3c3c;
    font-weight: bold;
}

.preview-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    margin: 1em 0;
}

.preview-content a {
    color: #66d9ef;
    text-decoration: underline;
}

.preview-content a:hover {
    color: #a6e22e;
}

/* 代码块样式增强 */
.preview-content pre[class*="language-"] {
    position: relative;
    background: #272822;
    border: 1px solid #555;
    border-radius: 6px;
    overflow: hidden;
    margin: 1em 0;
    line-height: 1.5;
}

.preview-content pre[class*="language-"].line-numbers {
    padding-left: 3em;
}

.preview-content .line-numbers .line-numbers-rows {
    position: absolute;
    pointer-events: none;
    top: 0;
    font-size: 100%;
    left: -3.8em;
    width: 3em;
    letter-spacing: -1px;
    border-right: 1px solid #555;
    user-select: none;
}

.preview-content .line-numbers-rows > span {
    pointer-events: none;
    display: block;
    counter-increment: linenumber;
}

.preview-content .line-numbers-rows > span:before {
    content: counter(linenumber);
    color: #75715e;
    display: block;
    padding-right: 0.8em;
    text-align: right;
}

/* Prism工具栏样式 */
.preview-content .toolbar {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(60, 60, 60, 0.9);
    border-radius: 0 6px 0 6px;
    padding: 4px;
}

.preview-content .toolbar .toolbar-item {
    display: inline-block;
    margin: 0 2px;
}

.preview-content .toolbar button {
    background: #66d9ef;
    color: #272822;
    border: none;
    padding: 4px 8px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 11px;
    font-weight: bold;
}

.preview-content .toolbar button:hover {
    background: #a6e22e;
}

/* 代码折叠功能 */
/* 代码块按钮容器 */
.code-btn-container {
    position: absolute !important;
    top: 8px !important;
    right: 12px !important;
    z-index: 100 !important;
    display: flex !important;
    gap: 4px !important;
}

.code-fold-btn,
.code-copy-btn {
    background: #4a4a4a !important;
    color: #f8f8f2 !important;
    border: 1px solid #666 !important;
    padding: 4px 8px !important;
    font-size: 11px !important;
    border-radius: 3px !important;
    cursor: pointer !important;
    transition: all 0.2s ease !important;
    opacity: 0.9 !important;
    font-family: Arial, sans-serif !important;
    line-height: 1 !important;
    min-width: 36px !important;
    text-align: center !important;
    white-space: nowrap !important;
}

.code-copy-btn {
    background: #2d5a87 !important;
}

.code-copy-btn.copied {
    background: #28a745 !important;
}

.code-fold-btn:hover,
.code-copy-btn:hover {
    opacity: 1 !important;
    transform: scale(1.05) !important;
    box-shadow: 0 2px 4px rgba(0,0,0,0.3) !important;
}

.code-fold-btn:hover {
    background: #666 !important;
}

.code-copy-btn:hover {
    background: #3d7bb7 !important;
}

.code-fold-btn:active,
.code-copy-btn:active {
    transform: scale(0.95) !important;
}

.code-fold-btn:active {
    background: #333 !important;
}

.code-copy-btn:active {
    background: #1e4a6b !important;
}

/* 代码块容器样式 */
pre[class*="language-"],
pre.line-numbers {
    position: relative !important;
    margin: 16px 0 !important;
    border-radius: 8px !important;
    overflow: hidden !important;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3) !important;
    border: 1px solid #444 !important;
    transition: max-height 0.3s ease !important;
}

/* 折叠状态的代码块样式 */
pre.code-folded {
    max-height: 60px !important;
    overflow: hidden !important;
}

pre.code-folded code {
    opacity: 0.6 !important;
    filter: blur(1px) !important;
    transition: opacity 0.3s ease, filter 0.3s ease !important;
}

pre.code-folded::after {
    content: '... (代码已折叠，点击"展开"查看完整内容)' !important;
    position: absolute !important;
    bottom: 8px !important;
    left: 50% !important;
    transform: translateX(-50%) !important;
    background: rgba(0,0,0,0.8) !important;
    color: #f8f8f2 !important;
    padding: 6px 12px !important;
    border-radius: 12px !important;
    font-size: 11px !important;
    font-style: italic !important;
    border: 1px solid #666 !important;
    z-index: 10 !important;
    border: 1px dashed #75715e;
}

/* 确保代码块有相对定位，以便按钮绝对定位 */
.preview-content pre {
    position: relative;
}

/* 预览区域样式 */
.preview-content {
    padding: 20px;
    height: 100%;
    overflow-y: auto;
    background: #2b2b2b;
    color: #f8f8f2;
}

/* 文本选择和链接功能 */
.text-selection-menu {
    position: absolute;
    background: #333;
    border: 1px solid #555;
    border-radius: 4px;
    padding: 8px;
    z-index: 10001;
    display: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.5);
}

.text-selection-menu button {
    background: #444;
    color: #f8f8f2;
    border: none;
    padding: 6px 12px;
    margin: 2px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
}

.text-selection-menu button:hover {
    background: #555;
}

/* ID标识样式 */
.text-with-id {
    background: rgba(102, 217, 239, 0.3);
    border-bottom: 2px solid #66d9ef;
    position: relative;
    cursor: pointer;
}

.text-with-id::after {
    content: attr(data-id);
    position: absolute;
    top: -20px;
    left: 0;
    background: #66d9ef;
    color: #272822;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 10px;
    font-weight: bold;
    white-space: nowrap;
    opacity: 0;
    transition: opacity 0.3s;
}

.text-with-id:hover::after {
    opacity: 1;
}

/* 链接管理面板 */
.link-manager {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #2b2b2b;
    border: 1px solid #555;
    border-radius: 8px;
    padding: 20px;
    min-width: 400px;
    max-height: 80vh;
    overflow-y: auto;
    z-index: 10002;
    color: #f8f8f2;
    display: none;
}

.link-manager h3 {
    color: #f92672;
    margin-top: 0;
}

.link-item {
    padding: 10px;
    margin: 8px 0;
    background: #3c3c3c;
    border-radius: 4px;
    border-left: 4px solid #66d9ef;
}

.link-item .source {
    font-weight: bold;
    color: #a6e22e;
}

.link-item .target {
    color: #e6db74;
    margin-top: 4px;
}

/* 链接对话框样式 */
.link-dialog .link-dialog-content {
    background: #2b2b2b;
    color: #f8f8f2;
}

.link-dialog h4 {
    color: #f92672;
    margin-top: 0;
    margin-bottom: 15px;
}

.link-dialog .form-group {
    margin-bottom: 15px;
}

.link-dialog label {
    display: block;
    margin-bottom: 5px;
    color: #a6e22e;
    font-weight: bold;
}

.link-dialog select,
.link-dialog input {
    width: 100%;
    padding: 8px 12px;
    background: #3c3c3c;
    color: #f8f8f2;
    border: 1px solid #555;
    border-radius: 4px;
    font-size: 14px;
}

.link-dialog select:focus,
.link-dialog input:focus {
    outline: none;
    border-color: #66d9ef;
    box-shadow: 0 0 5px rgba(102, 217, 239, 0.3);
}

.link-input-container {
    display: flex;
    gap: 8px;
    align-items: center;
}

.link-input-container input {
    flex: 1;
}

.link-input-container button {
    padding: 8px 12px;
    background: #66d9ef;
    color: #272822;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
    white-space: nowrap;
}

.link-input-container button:hover {
    background: #a6e22e;
}

/* 链接选择器样式 */
.link-selector {
    margin-top: 15px;
    border: 1px solid #555;
    border-radius: 6px;
    background: #333;
    max-height: 300px;
    overflow: hidden;
}

.selector-header {
    padding: 10px;
    background: #3c3c3c;
    border-bottom: 1px solid #555;
    display: flex;
    gap: 10px;
    align-items: center;
}

.selector-header input {
    flex: 1;
    margin: 0;
    padding: 6px 10px;
    font-size: 13px;
}

.search-count {
    color: #75715e;
    font-size: 12px;
    white-space: nowrap;
}

.selector-content {
    max-height: 240px;
    overflow-y: auto;
    padding: 5px;
}

.selector-option {
    padding: 10px;
    margin: 3px;
    background: #2b2b2b;
    border: 1px solid #555;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.selector-option:hover {
    background: #3c3c3c;
    border-color: #66d9ef;
}

.selector-option.selected {
    background: #66d9ef;
    color: #272822;
    border-color: #a6e22e;
}

.selector-option.selected .option-title {
    color: #272822;
    font-weight: bold;
}

.option-title {
    font-weight: bold;
    color: #a6e22e;
    margin-bottom: 4px;
    font-size: 14px;
}

.option-preview {
    color: #f8f8f2;
    font-size: 12px;
    line-height: 1.4;
    margin-bottom: 4px;
    opacity: 0.8;
}

.option-source {
    color: #75715e;
    font-size: 11px;
    margin-bottom: 4px;
}

.option-link {
    color: #e6db74;
    font-size: 11px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    background: rgba(0,0,0,0.3);
    padding: 2px 6px;
    border-radius: 3px;
    display: inline-block;
}

.no-options {
    text-align: center;
    color: #75715e;
    padding: 20px;
    font-style: italic;
}

.link-dialog .btn-group {
    text-align: right;
    margin-top: 20px;
}

.link-dialog .btn-group button {
    margin-left: 8px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
}

.link-dialog .btn-group button:first-child {
    background: #75715e;
    color: #f8f8f2;
}

.link-dialog .btn-group button:last-child {
    background: #66d9ef;
    color: #272822;
}

.link-dialog .btn-group button:hover {
    opacity: 0.8;
}

/* 锚点跳转动画效果 */
@keyframes anchorBlink {
    0% { 
        transform: scale(1); 
        box-shadow: 0 0 0 rgba(249, 38, 114, 0.5);
    }
    50% { 
        transform: scale(1.1); 
        box-shadow: 0 0 15px rgba(249, 38, 114, 0.8);
        background-color: rgba(249, 38, 114, 0.3);
    }
    100% { 
        transform: scale(1); 
        box-shadow: 0 0 0 rgba(249, 38, 114, 0.5);
    }
}

.anchor-target {
    animation: anchorBlink 0.6s ease-in-out 3;
    border-radius: 4px;
    padding: 2px 4px;
}

/* 锚点链接样式 */
a[href^="#"] {
    color: #e6db74;
    text-decoration: underline;
    cursor: pointer;
    transition: all 0.3s ease;
}

a[href^="#"]:hover {
    color: #a6e22e;
    text-decoration: none;
    background-color: rgba(166, 226, 46, 0.2);
    border-radius: 3px;
    padding: 1px 3px;
}

/* 热点链接特殊样式 */
a[href^="#hotspot-"] {
    color: #66d9ef;
    border-bottom: 1px dotted #66d9ef;
}

a[href^="#hotspot-"]:hover {
    color: #f92672;
    border-bottom-color: #f92672;
    background-color: rgba(102, 217, 239, 0.2);
}

/* 改进的ID标识样式 */
.text-with-id {
    background: rgba(102, 217, 239, 0.2);
    border-bottom: 2px solid #66d9ef;
    position: relative;
    cursor: pointer;
    transition: all 0.3s ease;
    padding: 0 2px;
    border-radius: 2px;
    scroll-margin-top: 100px; /* 为锚点跳转留出空间 */
}

.text-with-id:hover {
    background: rgba(102, 217, 239, 0.4);
    border-bottom-color: #a6e22e;
}

.text-with-id[data-link-id] {
    color: #66d9ef;
    text-decoration: none;
}

.text-with-id[data-link-id]:hover {
    color: #a6e22e;
}

/* 标题锚点样式 */
h1[id], h2[id], h3[id], h4[id], h5[id], h6[id] {
    scroll-margin-top: 100px;
    position: relative;
}

h1[id]:hover::before, h2[id]:hover::before, h3[id]:hover::before, 
h4[id]:hover::before, h5[id]:hover::before, h6[id]:hover::before {
    content: "🔗";
    position: absolute;
    left: -30px;
    color: #66d9ef;
    font-size: 0.8em;
    opacity: 0.7;
}

/* 代码块中的链接样式 */
.preview-content pre .text-with-id {
    background: rgba(166, 226, 46, 0.2);
    border-bottom-color: #a6e22e;
    color: #a6e22e;
}

.preview-content pre .text-with-id:hover {
    background: rgba(166, 226, 46, 0.4);
    color: #66d9ef;
}

/* 底部操作栏 */
.modal-footer {
    background: #333;
    padding: 15px 20px;
    border-top: 1px solid #555;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-footer button {
    background: #66d9ef;
    color: #272822;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
    margin-left: 8px;
}

.modal-footer button:hover {
    background: #a6e22e;
}

.modal-footer button.secondary {
    background: #75715e;
    color: #f8f8f2;
}

.modal-footer button.secondary:hover {
    background: #555;
}

/* 默认显示热点可视化层，让功能正常工作 */
.hotspot-overlay {
    display: block;
}

/* 在Dreamweaver编辑模式下隐藏热点可视化层 */
.dreamweaver-edit .hotspot-overlay {
    display: none;
}

/* ================================
   多窗口管理系统样式
   ================================ */

/* 窗口管理器 - 模仿Windows任务栏 */
.window-manager {
    position: fixed;
    bottom: 0; /* 贴着浏览器底部 */
    left: 0;
    right: 0;
    height: 48px;
    background: rgba(30, 30, 30, 0.95);
    border-top: 1px solid #555;
    backdrop-filter: blur(15px);
    z-index: 20000;
    display: flex;
    align-items: center;
    padding: 0 10px;
    transition: all 0.3s ease;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3);
}

.window-manager.minimized {
    height: 32px;
    background: rgba(30, 30, 30, 0.8);
}

.window-manager.minimized .manager-header {
    display: none;
}

.window-manager.minimized .window-list {
    height: 100%;
}

.manager-header {
    color: #f8f8f2;
    font-size: 12px;
    font-weight: bold;
    margin-right: 15px;
    padding: 0 10px;
    border-right: 1px solid #555;
    white-space: nowrap;
    display: flex;
    align-items: center;
    height: 100%;
}

.window-list {
    display: flex;
    align-items: center;
    gap: 5px;
    flex: 1;
    overflow-x: auto;
    overflow-y: hidden;
    height: 100%;
    padding: 4px 0;
}

.window-list::-webkit-scrollbar {
    height: 3px;
}

.window-list::-webkit-scrollbar-track {
    background: transparent;
}

.window-list::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 3px;
}

.window-item {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 120px;
    max-width: 200px;
    height: 36px;
    background: rgba(60, 60, 60, 0.8);
    border: 1px solid #555;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 11px;
    color: #f8f8f2;
    position: relative;
    overflow: hidden;
    padding: 0 8px;
    box-sizing: border-box;
}

.window-item:hover {
    background: rgba(80, 80, 80, 0.9);
    border-color: #777;
    transform: translateY(-1px);
}

.window-item.active {
    background: #a6e22e;
    color: #272822;
    border-color: #a6e22e;
    box-shadow: 0 0 10px rgba(166, 226, 46, 0.3);
}

.window-item.active::before {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: #272822;
}

.window-item .window-title {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: center;
    font-weight: 500;
    margin-right: 5px;
}

.window-item .window-controls {
    display: flex;
    gap: 2px;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.window-item:hover .window-controls {
    opacity: 1;
}

.window-control-btn {
    width: 16px;
    height: 16px;
    border: none;
    border-radius: 2px;
    cursor: pointer;
    font-size: 10px;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.window-control-btn:hover {
    transform: scale(1.1);
}

.minimize-btn {
    background: #f5c842;
    color: #000;
}

.close-btn {
    background: #f85149;
    color: #fff;
}

.activate-btn {
    background: #56d364;
    color: #000;
}

/* 多窗口模态框系统 */
.multi-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10000;
    pointer-events: none;
}

.window-container {
    position: absolute;
    background: #272822;
    border: 1px solid #555;
    border-radius: 8px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    min-width: 400px;
    min-height: 300px;
    max-width: 95vw;
    max-height: 95vh;
    pointer-events: all;
    overflow: hidden;
    transition: all 0.3s ease;
    resize: both; /* 允许浏览器原生调整大小 */
}

.window-container.minimized {
    transform: scale(0);
    opacity: 0;
    pointer-events: none;
}

.window-container.active {
    z-index: 15000;
    box-shadow: 0 15px 40px rgba(166, 226, 46, 0.3);
    border-color: #a6e22e;
}

.window-container.maximized {
    border-radius: 0; /* 最大化时去掉圆角 */
    transition: none; /* 最大化时禁用动画 */
}

.window-container.maximized .window-resize-handle {
    display: none; /* 最大化时隐藏调整大小手柄 */
}

/* 窗口拖拽调整大小手柄 */
.window-resize-handle {
    position: absolute;
    background: transparent;
    z-index: 10;
}

.window-resize-handle:hover {
    background: rgba(166, 226, 46, 0.2);
}

.window-resize-handle.n {
    top: -3px;
    left: 3px;
    right: 3px;
    height: 6px;
    cursor: n-resize;
}

.window-resize-handle.s {
    bottom: -3px;
    left: 3px;
    right: 3px;
    height: 6px;
    cursor: s-resize;
}

.window-resize-handle.w {
    left: -3px;
    top: 3px;
    bottom: 3px;
    width: 6px;
    cursor: w-resize;
}

.window-resize-handle.e {
    right: -3px;
    top: 3px;
    bottom: 3px;
    width: 6px;
    cursor: e-resize;
}

.window-resize-handle.nw {
    top: -3px;
    left: -3px;
    width: 12px;
    height: 12px;
    cursor: nw-resize;
}

.window-resize-handle.ne {
    top: -3px;
    right: -3px;
    width: 12px;
    height: 12px;
    cursor: ne-resize;
}

.window-resize-handle.sw {
    bottom: -3px;
    left: -3px;
    width: 12px;
    height: 12px;
    cursor: sw-resize;
}

.window-resize-handle.se {
    bottom: -3px;
    right: -3px;
    width: 12px;
    height: 12px;
    cursor: se-resize;
}

/* 调整大小时的视觉反馈 */
.window-container.resizing {
    transition: none;
    user-select: none;
}

.window-header {
    background: #3c3c3c;
    color: #f8f8f2;
    padding: 8px 12px;
    border-bottom: 1px solid #555;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: move;
    user-select: none;
}

.window-title {
    font-weight: bold;
    font-size: 13px;
}

.window-controls {
    display: flex;
    gap: 6px;
}

.window-controls button {
    width: 18px;
    height: 18px;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    font-size: 11px;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

.window-controls .minimize {
    background: #f5c842;
    color: #000;
}

.window-controls .close {
    background: #f85149;
    color: #fff;
}

.window-content {
    height: calc(100% - 45px);
    overflow: auto;
    background: #272822;
}

/* 图片添加模态框样式 */
.add-image-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 10001;
    backdrop-filter: blur(2px);
}

.add-image-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    max-width: 600px;
    width: 90%;
}

/* 图片容器删除按钮 */
.image-container {
    position: relative;
}

.image-delete-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 30px;
    height: 30px;
    background: #dc3545;
    color: white;
    border: 2px solid white;
    border-radius: 50%;
    cursor: pointer;
    font-size: 16px;
    line-height: 26px;
    text-align: center;
    z-index: 100;
    display: none;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    transition: all 0.3s ease;
}

/* 只有在编辑模式下才显示图片删除按钮 */
.drawing-mode .image-container:hover .image-delete-btn {
    display: block;
}

.image-delete-btn:hover {
    background: #c82333;
    transform: scale(1.1);
}

/* 剪贴板上传区域 */
.clipboard-upload-area {
    border: 2px dashed #007bff;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background: #f8f9fa;
    margin: 10px 0;
    cursor: pointer;
    transition: all 0.3s ease;
}

.clipboard-upload-area:hover {
    border-color: #0056b3;
    background: #e9ecef;
}

.clipboard-upload-area.dragover {
    border-color: #28a745;
    background: #d4edda;
}

.clipboard-upload-area .upload-icon {
    font-size: 24px;
    color: #007bff;
    margin-bottom: 10px;
}

/* 热点编辑模态框样式 */
.hotspot-editor-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 10002;
    backdrop-filter: blur(2px);
}

.hotspot-editor-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    max-width: 800px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
}

/* 编辑模式下的热点样式 */
.drawing-mode .hotspot-area {
    background: rgba(255, 193, 7, 0.3) !important;
    border: 2px dashed rgba(255, 193, 7, 0.8) !important;
    cursor: move !important;
    /* 保持原有的位置和尺寸，不改变position */
    /* 只改变背景色和边框样式，保持位置不变 */
}

.drawing-mode .hotspot-area:hover {
    background: rgba(255, 193, 7, 0.5) !important;
    border-color: rgba(255, 193, 7, 1) !important;
}

/* Ctrl连续绘画模式的特殊样式 */
body.drawing-mode.continuous-draw-mode {
    background: linear-gradient(45deg, transparent 48%, rgba(0, 123, 255, 0.05) 49%, rgba(0, 123, 255, 0.05) 51%, transparent 52%);
    background-size: 20px 20px;
}

body.drawing-mode.continuous-draw-mode .hotspot-area {
    background: rgba(0, 123, 255, 0.4) !important;
    border: 2px solid rgba(0, 123, 255, 0.9) !important;
    box-shadow: 0 0 10px rgba(0, 123, 255, 0.5) !important;
}

body.drawing-mode.continuous-draw-mode .hotspot-area:hover {
    background: rgba(0, 123, 255, 0.6) !important;
    border-color: rgba(0, 123, 255, 1) !important;
}

/* 移动中的热点样式 */
.moving-hotspot {
    background: rgba(255, 0, 0, 0.4) !important;
    border: 2px solid rgba(255, 0, 0, 0.9) !important;
    cursor: grabbing !important;
    z-index: 1000 !important;
    box-shadow: 0 4px 12px rgba(255, 0, 0, 0.3) !important;
    transform: scale(1.05) !important;
    transition: none !important; /* 移动时禁用过渡动画 */
}

/* 绘制模式下的删除按钮 */
.drawing-mode .hotspot-area .delete-btn {
    position: absolute !important;
    top: -8px !important;
    right: -8px !important;
    width: 20px !important;
    height: 20px !important;
    background: #dc3545 !important;
    color: white !important;
    border: 2px solid white !important;
    border-radius: 50% !important;
    cursor: pointer !important;
    font-size: 12px !important;
    line-height: 16px !important;
    text-align: center !important;
    z-index: 30 !important;
    display: none;
    box-shadow: 0 2px 4px rgba(0,0,0,0.3) !important;
}

/* 绘制模式下的调节手柄 */
.drawing-mode .hotspot-area .resize-handle {
    position: absolute !important;
    width: 8px !important;
    height: 8px !important;
    background: #007bff !important;
    border: 1px solid white !important;
    z-index: 25 !important;
    display: none;
    box-shadow: 0 1px 3px rgba(0,0,0,0.3) !important;
}

.drawing-mode .hotspot-area:hover .resize-handle {
    display: block;
}

.resize-handle.nw { top: -4px !important; left: -4px !important; cursor: nw-resize !important; }
.resize-handle.ne { top: -4px !important; right: -4px !important; cursor: ne-resize !important; }
.resize-handle.sw { bottom: -4px !important; left: -4px !important; cursor: sw-resize !important; }
.resize-handle.se { bottom: -4px !important; right: -4px !important; cursor: se-resize !important; }

/* 调节中的热点样式 */
.resizing-hotspot {
    background: rgba(0, 123, 255, 0.4) !important;
    border: 2px solid rgba(0, 123, 255, 1) !important;
    z-index: 1000 !important;
}

.drawing-mode .hotspot-area:hover .delete-btn {
    display: block;
}

.drawing-mode .hotspot-area .delete-btn:hover {
    background: #c82333;
    transform: scale(1.1);
}

/* 表单样式 */
.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

        /* 右上角提示框样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
            max-width: 400px;
            pointer-events: none;
        }
        
        .toast {
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            margin-bottom: 10px;
            padding: 16px 20px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.3s ease;
            pointer-events: auto;
            border-left: 4px solid;
            white-space: pre-wrap;
            word-break: break-word;
        }
        
        .toast.show {
            transform: translateX(0);
            opacity: 1;
        }
        
        .toast.hide {
            transform: translateX(100%);
            opacity: 0;
        }
        
        .toast-success {
            border-left-color: #28a745;
        }
        
        .toast-error {
            border-left-color: #dc3545;
        }
        
        .toast-warning {
            border-left-color: #ffc107;
        }
        
        .toast-info {
            border-left-color: #17a2b8;
        }
        
        .toast-icon {
            font-size: 18px;
            line-height: 1;
            margin-top: 1px;
        }
        
        .toast-content {
            flex: 1;
            font-size: 14px;
            line-height: 1.4;
            color: #333;
        }
        
        .toast-close {
            background: none;
            border: none;
            font-size: 16px;
            color: #666;
            cursor: pointer;
            padding: 0;
            margin-left: auto;
            opacity: 0.7;
            transition: opacity 0.2s;
        }
        
        .toast-close:hover {
            opacity: 1;
        }

        /* 框选工具样式 */
        .selection-box {
            position: fixed;
            border: 2px dashed #007bff;
            background: rgba(0, 123, 255, 0.1);
            pointer-events: none;
            z-index: 9999;
            display: none;
        }
        
        .hotspot-area.selected-hotspot {
            background: rgba(255, 140, 0, 0.6) !important;
            border: 4px solid rgba(255, 140, 0, 1) !important;
            box-shadow: 0 0 20px rgba(255, 140, 0, 0.8) !important;
            z-index: 150 !important;
            animation: pulse-selection 1.5s infinite !important;
            transform: scale(1.05) !important;
        }
        
        /* 确保在绘制模式下也能显示选中样式 */
        .drawing-mode .hotspot-area.selected-hotspot {
            background: rgba(255, 140, 0, 0.7) !important;
            border: 4px solid rgba(255, 140, 0, 1) !important;
            box-shadow: 0 0 20px rgba(255, 140, 0, 0.9) !important;
        }
        
        @keyframes pulse-selection {
            0% { 
                box-shadow: 0 0 20px rgba(255, 140, 0, 0.8) !important;
                transform: scale(1.05) !important;
            }
            50% { 
                box-shadow: 0 0 30px rgba(255, 140, 0, 1) !important;
                transform: scale(1.08) !important;
            }
            100% { 
                box-shadow: 0 0 20px rgba(255, 140, 0, 0.8) !important;
                transform: scale(1.05) !important;
            }
        }
        
        .context-menu {
            position: fixed;
            background: white;
            border: 1px solid #ccc;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            padding: 8px 0;
            z-index: 10001;
            min-width: 150px;
            display: none;
        }
        
        .context-menu-item {
            padding: 8px 16px;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .context-menu-item:hover {
            background: #f8f9fa;
        }
        
        .context-menu-item.danger {
            color: #dc3545;
        }
        
        .context-menu-item.danger:hover {
            background: #f8d7da;
        }

        /* 自定义弹窗样式 */
        .custom-modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }

.custom-modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 0;
    border-radius: 10px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    animation: slideIn 0.3s ease;
    position: relative;
}

.custom-modal-header {
    padding: 20px 25px 15px 25px;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.custom-modal-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.custom-modal-close {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    line-height: 1;
    transition: color 0.3s ease;
}

.custom-modal-close:hover {
    color: #000;
}

.custom-modal-body {
    padding: 20px 25px;
    color: #333;
    line-height: 1.6;
    white-space: pre-line;
    max-height: 300px;
    overflow-y: auto;
}

.custom-modal-footer {
    padding: 15px 25px 20px 25px;
    border-top: 1px solid #e9ecef;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.custom-modal-btn {
    padding: 8px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.custom-modal-btn-primary {
    background-color: #007bff;
    color: white;
}

.custom-modal-btn-primary:hover {
    background-color: #0056b3;
}

.custom-modal-btn-secondary {
    background-color: #6c757d;
    color: white;
}

.custom-modal-btn-secondary:hover {
    background-color: #545b62;
}

.custom-modal-btn-danger {
    background-color: #dc3545;
    color: white;
}

.custom-modal-btn-danger:hover {
    background-color: #c82333;
}

.custom-modal-btn-success {
    background-color: #28a745;
    color: white;
}

.custom-modal-btn-success:hover {
    background-color: #1e7e34;
}

/* 动画效果 */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from { 
        transform: translateY(-50px);
        opacity: 0;
    }
    to { 
        transform: translateY(0);
        opacity: 1;
    }
}

/* 成功/错误/警告图标 */
.custom-modal-icon {
    display: inline-block;
    width: 24px;
    height: 24px;
    margin-right: 10px;
    vertical-align: middle;
}

.custom-modal-success {
    color: #28a745;
}

.custom-modal-error {
    color: #dc3545;
}

.custom-modal-warning {
    color: #ffc107;
}

    .custom-modal-info {
        color: #17a2b8;
    }
    
    /* 图片预览样式 */
    .image-preview-container {
        margin: 20px 0;
        padding: 15px;
        border: 2px dashed #e9ecef;
        border-radius: 8px;
        background: #f8f9fa;
    }
    
    .image-preview-container label {
        display: block;
        margin-bottom: 10px;
        font-weight: 600;
        color: #495057;
    }
    
    .image-preview-wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
    }
    
    .image-preview {
        max-width: 100%;
        max-height: 300px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        border: 2px solid #fff;
        object-fit: contain;
        background: #fff;
    }
    
    .image-info {
        display: flex;
        flex-direction: column;
        gap: 5px;
        text-align: center;
        font-size: 12px;
        color: #6c757d;
    }
    
    .image-name {
        font-weight: 600;
        color: #495057;
    }
    
    .image-size {
        color: #6c757d;
    }
    
    .image-dimensions {
        color: #6c757d;
    }
    
    /* 图片预览动画 */
    .image-preview-container.show {
        animation: slideDown 0.3s ease;
    }
    
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

.form-group input, .form-group textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.form-group textarea {
    height: 100px;
    resize: vertical;
}

.btn-group {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
}

.btn-primary {
    background: #007bff;
    color: white;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

/* 响应式布局 - 顶部导航栏 + 底部任务栏 */
@media (max-width: 768px) {
    body {
        padding: 60px 15px 55px 15px !important; /* 顶部60px，底部55px */
    }
    
    .window-manager {
        height: 44px !important; /* 稍微减小任务栏高度 */
        padding: 0 8px !important;
    }
    
    #fixedButtonBar {
        padding: 6px 10px !important;
        gap: 4px !important;
        max-height: 50px !important;
    }
}

@media (max-width: 480px) {
    body {
        padding: 50px 10px 45px 10px !important; /* 更小的间距 */
    }
    
    .window-manager {
        height: 40px !important;
        padding: 0 6px !important;
    }
    
    #fixedButtonBar {
        padding: 4px 8px !important;
        gap: 3px !important;
        max-height: 45px !important;
    }
    
/* 顶部导航栏样式优化 */
#fixedButtonBar {
    border-bottom: 1px solid rgba(255,255,255,0.1);
    font-size: 13px;
}

#fixedButtonBar button {
    background: rgba(255,255,255,0.1);
    color: white;
    border: none;
    border-radius: 6px;
    padding: 6px 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: inherit;
    font-weight: 500;
}

#fixedButtonBar button:hover {
    background: rgba(255,255,255,0.2);
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

#fixedButtonBar button:active {
    transform: translateY(0);
    background: rgba(255,255,255,0.15);
}

/* 隐藏按钮特殊样式 */
#fixedButtonBar button[onclick="toggleTopNavBar()"] {
    background: rgba(255,255,255,0.05);
    font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
    font-weight: 300;
    min-width: 24px;
}

#fixedButtonBar button[onclick="toggleTopNavBar()"]:hover {
    background: rgba(255,255,255,0.15);
}
</style>
</head>

<body>
<!-- 顶部导航栏（类似macOS状态栏） -->
<div id="fixedButtonBar" style="position: fixed; top: 0; left: 0; right: 0; background: rgba(0, 0, 0, 0.9); backdrop-filter: blur(10px); padding: 8px 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.3); z-index: 10000; display: flex; gap: 6px; justify-content: center; flex-wrap: wrap; align-items: center; max-height: 60px; overflow-y: auto; transition: transform 0.3s ease;">
    <!-- 左侧隐藏/显示按钮 -->
    <button id="toggleNavBtn" style="position: absolute; left: 8px; padding: 4px 8px; background: rgba(255,255,255,0.1); color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;" title="隐藏/显示导航栏 (Ctrl+Alt+H 或 ESC)">⌘</button>
    
    <!-- 测试按钮 -->
    <button onclick="alert('JavaScript正常工作！')" style="position: absolute; left: 45px; padding: 4px 8px; background: rgba(255,0,0,0.3); color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;" title="测试JavaScript">测试</button>
    
    <!-- 双击功能测试按钮 -->
    <button onclick="testDoubleClickFunction()" style="position: absolute; left: 135px; padding: 4px 8px; background: rgba(0,0,255,0.3); color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;" title="测试双击功能">双击测试</button>
    
    <!-- 简单切换按钮 -->
    <button onclick="simpleToggle()" style="position: absolute; left: 90px; padding: 4px 8px; background: rgba(0,255,0,0.3); color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;" title="简单切换">简单</button>
    
    <!-- 右侧状态指示器 -->
    <div style="position: absolute; right: 8px; color: rgba(255,255,255,0.6); font-size: 11px; display: flex; align-items: center; gap: 8px;">
        <span id="navBarStatus">显示</span>
        <span style="opacity: 0.4;">|</span>
        <span id="currentTime"></span>
    </div>
    
    <!-- 中间的功能按钮 -->>
    <button onClick="toggleEditMode()" style="padding: 10px 15px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">Dreamweaver编辑模式</button>
    <button onClick="showAddImageModal()" style="padding: 10px 15px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">添加图片</button>
    <button onClick="showHotspotEditor()" style="padding: 10px 15px; background: #ffc107; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">编辑热点</button>
        <button onClick="saveAllData()" style="padding: 10px 15px; background: #dc3545; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">💾 保存所有数据</button>
    <button onClick="showBackupManager()" style="padding: 10px 15px; background: #17a2b8; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">📦 备份管理</button>
    <button onClick="showOperationLogs()" style="padding: 10px 15px; background: #6f42c1; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">📋 操作日志</button>
    <button onClick="testSelectionDebug()" style="padding: 10px 15px; background: #ff6b35; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">🎯 测试选中</button>
    <button onClick="testEditor()" style="padding: 10px 15px; background: #e74c3c; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">🔧 测试编辑器</button>
    <button onClick="forceShowSelected()" style="padding: 10px 15px; background: #e74c3c; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">🔥 强制显示</button>
    <button onClick="saveToJson()" style="padding: 10px 15px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">导出JSON</button>
    <button onClick="refreshData()" style="padding: 10px 15px; background: #17a2b8; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">🔄 刷新数据</button>
    <button onClick="showDataInfo()" style="padding: 10px 15px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">📊 数据信息</button>
    <button onClick="testHotspotInfo()" style="padding: 10px 15px; background: #6f42c1; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">测试数据</button>
    <div style="margin-left: 20px; padding: 5px 10px; background: #e9ecef; border-radius: 5px; font-size: 12px; color: #495057;">
        <span id="saveStatus">未保存</span>
    </div>
    <div style="margin-left: 10px; padding: 5px 10px; background: #e9ecef; border-radius: 5px; font-size: 12px; color: #495057;">
        <span id="serverStatus">检查中...</span>
    </div>
    <div style="margin-left: 10px; padding: 5px 10px; background: #e9ecef; border-radius: 5px; font-size: 12px; color: #495057;">
        <span id="errorStatus" style="display: none;">⚠️ 错误</span>
    </div>
</div>

<!-- 自定义弹窗 -->
<div id="customModal" class="custom-modal">
    <div class="custom-modal-content">
        <div class="custom-modal-header">
            <h3 class="custom-modal-title" id="customModalTitle">提示</h3>
            <span class="custom-modal-close" onclick="closeCustomModal()">&times;</span>
        </div>
        <div class="custom-modal-body" id="customModalBody">
            消息内容
        </div>
        <div class="custom-modal-footer" id="customModalFooter">
            <button class="custom-modal-btn custom-modal-btn-primary" onclick="closeCustomModal()">确定</button>
        </div>
    </div>
</div>

<div class="container" style="margin-top: 80px;">
    <h1>地图热点展示</h1>
    <p>鼠标悬停在热点区域查看提示信息，点击查看详细信息</p>
         
                   <!-- 绘制新热点按钮 - 固定位置 -->
          <div id="drawingButtonContainer" style="display: block; position: fixed; top: 80px; right: 20px; z-index: 1000;">
              <button id="drawingButton" onClick="toggleDrawingMode()" style="padding: 15px 20px; background: #ff6b35; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; box-shadow: 0 4px 12px rgba(0,0,0,0.3);">
                  🎨 编辑模式
              </button>
          </div>
        
                 <div class="image-container" data-image-id="1">
             <div class="image-delete-btn" onclick="deleteImage(1)" title="删除图片">×</div>
             <img src="IMG/1.png" border="0" usemap="#Map" />
             <map name="Map" id="Map">
                 <area shape="rect" coords="830,133,1032,236" href="#1" />
                 <area shape="rect" coords="1282,370,1437,634" href="#2" />
                 <area shape="rect" coords="1294,1154,1462,1186" href="#3" />
             </map>
        <!-- 热点可视化层 -->
             <div class="hotspot-overlay">
                 <div class="hotspot-area" data-href="#1" style="left: 830px; top: 133px; width: 202px; height: 103px;"></div>
                 <div class="hotspot-area" data-href="#2" style="left: 1282px; top: 370px; width: 155px; height: 264px;"></div>
                 <div class="hotspot-area" data-href="#3" style="left: 1294px; top: 1154px; width: 168px; height: 32px;"></div>
        </div>
    </div>
         
                 <div class="image-container" data-image-id="2">
             <div class="image-delete-btn" onclick="deleteImage(2)" title="删除图片">×</div>
             <img src="IMG/wechat_2025-09-01_153533_589.png" border="0" usemap="#Map2" />
             <map name="Map2" id="Map2">
                 <area shape="rect" coords="412,327,708,429" href="#4" />
    </map>
             <!-- 热点可视化层 -->
           <div class="hotspot-overlay">
                 <div class="hotspot-area" data-href="#4" style="left: 412px; top: 327px; width: 296px; height: 102px;"></div>
           </div>
         </div>
                                                                      <!-- 图片ID 3已移除，因为文件IMG/3.png不存在 -->
         
                   <!-- 第四张图片 -->
          <div class="image-container" data-image-id="4">
              <div class="image-delete-btn" onclick="deleteImage(4)" title="删除图片">×</div>
              <img src="IMG/4.png" width="1625" height="1134" border="0" usemap="#Map4">
              <map name="Map4" id="Map4">
                  <area shape="rect" coords="1350,136,1559,193" href="#10" />
                  <area shape="rect" coords="241,119,1584,317" href="#11" />
                  <area shape="rect" coords="251,327,597,400" href="#12" />
                  <area shape="rect" coords="886,331,1456,394" href="#13" />
                  <area shape="rect" coords="828,812,1002,835" href="#14" />
                  <area shape="rect" coords="828,838,1005,854" href="#15" />
                  <area shape="rect" coords="958,794,998,812" href="#16" />
                  <area shape="rect" coords="1437,1049,1585,1097" href="#17" />
                  <area shape="rect" coords="1264,1049,1420,1100" href="#18" />
              </map>
        <!-- 热点可视化层 -->
              <div class="hotspot-overlay">
                  <div class="hotspot-area" data-href="#10" style="left: 1350px; top: 136px; width: 209px; height: 57px;"></div>
                  <div class="hotspot-area" data-href="#11" style="left: 241px; top: 119px; width: 1343px; height: 198px; z-index: 15;"></div>
                  <div class="hotspot-area" data-href="#12" style="left: 251px; top: 327px; width: 346px; height: 73px;"></div>
                  <div class="hotspot-area" data-href="#13" style="left: 886px; top: 331px; width: 570px; height: 63px;"></div>
                  <div class="hotspot-area" data-href="#14" style="left: 828px; top: 812px; width: 174px; height: 23px;"></div>
                  <div class="hotspot-area" data-href="#15" style="left: 828px; top: 838px; width: 177px; height: 16px;"></div>
                  <div class="hotspot-area" data-href="#16" style="left: 958px; top: 794px; width: 40px; height: 18px; z-index: 25;"></div>
                  <div class="hotspot-area" data-href="#17" style="left: 1437px; top: 1049px; width: 148px; height: 48px;"></div>
                  <div class="hotspot-area" data-href="#18" style="left: 1264px; top: 1049px; width: 156px; height: 51px;"></div>
        </div>
    </div>
         
                   <!-- 第五张图片 -->
          <div class="image-container" data-image-id="5">
              <div class="image-delete-btn" onclick="deleteImage(5)" title="删除图片">×</div>
              <img src="IMG/5.png" width="720" height="740" border="0" usemap="#Map5">
              <map name="Map5" id="Map5">
                  <area shape="rect" coords="109,73,509,566" href="#19" />
    </map>
              <!-- 热点可视化层 -->
              <div class="hotspot-overlay">
                  <div class="hotspot-area" data-href="#19" style="left: 109px; top: 73px; width: 400px; height: 493px;"></div>
              </div>
          </div>

          <!-- 恢复的SVG图片 -->
          <div class="image-container" data-image-id="11">
              <div class="image-delete-btn" onclick="deleteImage(11)" title="删除图片">×</div>
              <img src="IMG/clipboard_1756882178268.svg" border="0" usemap="#Map11">
              <map name="Map11" id="Map11">
              </map>
              <!-- 热点可视化层 -->
              <div class="hotspot-overlay">
              </div>
          </div>
</div>

<!-- 工具提示 -->
<div id="tooltip" class="tooltip"></div>

         <!-- 弹窗 -->
     <div id="modal" class="modal-overlay">
         <div class="modal-content">
             <div class="modal-header">
                 <h3 class="modal-title">热点信息编辑器</h3>
                 <button class="close-btn" onClick="closeModal()">&times;</button>
             </div>
             <div class="modal-body">
                 <div class="editor-container">
                     <div class="editor-pane">
                         <div class="pane-header">
                             Markdown 编辑器
                             <span style="float: right; font-size: 12px; color: #75715e;">
                                 支持代码高亮、图片、链接等
                             </span>
                         </div>
                         <div class="editor-content">
                             <textarea id="markdown-editor" class="markdown-editor" 
                                       placeholder="请输入Markdown内容...&#10;&#10;支持功能：&#10;- 代码语法高亮 (```javascript)&#10;- 图片显示 ![alt](url)&#10;- 链接 [text](url)&#10;- 表格、列表等&#10;&#10;选中文字可添加链接和ID标识"></textarea>
                         </div>
                     </div>
                     <div class="editor-pane">
                         <div class="pane-header">
                             实时预览
                             <span style="float: right; font-size: 12px; color: #75715e;">
                                 双击文字可添加链接
                             </span>
                         </div>
                         <div class="editor-content">
                             <div id="preview-content" class="preview-content"></div>
                         </div>
                     </div>
                 </div>
             </div>
             <div class="modal-footer">
                 <div>
                     <button class="secondary" onclick="showLinkManager()">链接管理</button>
                     <button class="secondary" onclick="insertTemplate()">插入模板</button>
                     <button class="secondary" onclick="uploadImage()">上传图片</button>
                     <button class="secondary" onclick="copyToClipboard()">复制内容</button>
                 </div>
                 <div>
                     <button class="secondary" onclick="closeModal()">取消</button>
                     <button onclick="saveHotspotContent()">保存</button>
                 </div>
             </div>
         </div>
     </div>

     <!-- 文本选择菜单 -->
     <div id="text-selection-menu" class="text-selection-menu">
         <button onclick="addLinkToSelection()">添加链接</button>
         <button onclick="addIdToSelection()">添加ID</button>
         <button onclick="removeIdFromSelection()">移除ID</button>
     </div>

     <!-- 链接管理面板 -->
     <div id="link-manager" class="link-manager">
         <h3>链接管理</h3>
         <div id="link-list"></div>
         <button onclick="closeLinkManager()">关闭</button>
     </div>

           <!-- 添加图片模态框 -->
      <div id="addImageModal" class="add-image-modal">
          <div class="add-image-content">
              <h3>添加新图片</h3>
              
              <!-- 剪贴板上传区域 -->
              <div class="clipboard-upload-area" id="clipboardUploadArea">
                  <div class="upload-icon">📋</div>
                  <p><strong>从剪贴板上传图片</strong></p>
                  <p>复制图片后，点击此区域或按 Ctrl+V 粘贴</p>
                  <p style="font-size: 12px; color: #666;">支持截图、复制的图片等</p>
              </div>
              
              <div style="text-align: center; margin: 15px 0; color: #666;">或者</div>
              
              <div class="form-group">
                  <label for="imageFile">选择图片文件：</label>
                  <input type="file" id="imageFile" accept="image/*,.svg" onChange="handleFileSelect()" />
              </div>
              <div class="form-group">
                  <label for="imageName">图片名称：</label>
                  <input type="text" id="imageName" placeholder="例如：IMG/6.png" />
              </div>
              
              <!-- 图片预览区域 -->
              <div class="image-preview-container" id="imagePreviewContainer" style="display: none;">
                  <label>图片预览：</label>
                  <div class="image-preview-wrapper">
                      <img id="imagePreview" class="image-preview" alt="图片预览" />
                      <div class="image-info" id="imageInfo">
                          <span class="image-name" id="previewImageName"></span>
                          <span class="image-size" id="previewImageSize"></span>
                          <span class="image-dimensions" id="previewImageDimensions"></span>
                      </div>
                  </div>
              </div>
              
              <div class="btn-group">
                  <button class="btn btn-secondary" onClick="closeAddImageModal()">取消</button>
                  <button class="btn btn-primary" onClick="addNewImage()">添加图片</button>
              </div>
          </div>
      </div>
     
                       <!-- 热点编辑模态框 -->
       <div id="hotspotEditorModal" class="hotspot-editor-modal">
           <div class="hotspot-editor-content">
               <h3>热点编辑器</h3>
               <div id="hotspotList">
                   <!-- 热点列表将在这里动态生成 -->
               </div>
               <div class="btn-group">
                   <button class="btn btn-secondary" onClick="closeHotspotEditor()">关闭</button>
        </div>
    </div>
</div>

       <!-- 热点信息编辑模态框 -->
       <div id="hotspotInfoModal" class="hotspot-editor-modal">
           <div class="hotspot-editor-content">
               <h3>编辑热点信息</h3>
               <div class="form-group">
                   <label for="hotspotInfoTextarea">热点备注信息：</label>
                   <textarea id="hotspotInfoTextarea" rows="8" placeholder="请输入热点备注信息..."></textarea>
               </div>
               <div class="btn-group">
                   <button class="btn btn-secondary" onClick="closeHotspotInfoModal()">取消</button>
                   <button class="btn btn-primary" onClick="saveHotspotInfo()">保存</button>
               </div>
           </div>
       </div>

       <!-- 备份管理模态框 -->
       <div id="backupManagerModal" class="hotspot-editor-modal">
           <div class="hotspot-editor-content">
               <h3>备份管理</h3>
               <div id="backupList">
                   <p>正在加载备份列表...</p>
               </div>
               <div class="btn-group">
                   <button class="btn btn-secondary" onClick="closeBackupManager()">关闭</button>
                   <button class="btn btn-primary" onClick="refreshBackupList()">刷新</button>
               </div>
           </div>
       </div>

<script>
// =====================================
// 导航栏切换功能
// =====================================

// 简单版本的切换函数
function simpleToggle() {
    console.log('🔧 simpleToggle 被调用');
    const nav = document.getElementById('fixedButtonBar');
    if (nav) {
        if (nav.style.display === 'none') {
            nav.style.display = 'flex';
            document.body.style.paddingTop = '70px';
            console.log('✅ 导航栏显示');
        } else {
            nav.style.display = 'none';
            document.body.style.paddingTop = '20px';
            console.log('✅ 导航栏隐藏');
        }
    } else {
        console.error('❌ 找不到导航栏');
    }
}

// 测试双击功能
function testDoubleClickFunction() {
    console.log('🔧 测试双击功能被调用');
    
    // 测试模态框是否存在
    const modal = document.getElementById('hotspotInfoModal');
    const textarea = document.getElementById('hotspotInfoTextarea');
    
    console.log('模态框元素:', modal);
    console.log('文本框元素:', textarea);
    
    if (modal && textarea) {
        // 直接显示模态框进行测试
        modal.style.display = 'block';
        textarea.value = '这是一个测试信息';
        setTimeout(() => {
            textarea.focus();
        }, 100);
        alert('双击功能测试：模态框应该已显示');
    } else {
        alert('错误：找不到模态框或文本框元素');
        console.error('模态框或文本框未找到');
    }
}

// 更好的切换函数（使用transform）
function toggleTopNavBar() {
    console.log('🔧 toggleTopNavBar 函数被调用');
    
    const topNavBar = document.getElementById('fixedButtonBar');
    const body = document.body;
    const statusElement = document.getElementById('navBarStatus');
    
    console.log('🔍 元素查找结果:', {
        topNavBar: !!topNavBar,
        body: !!body,
        statusElement: !!statusElement
    });
    
    if (!topNavBar) {
        console.error('❌ 找不到 fixedButtonBar 元素');
        return;
    }
    
    try {
        const isHidden = topNavBar.style.transform === 'translateY(-100%)';
        
        if (!isHidden) {
            // 隐藏导航栏
            console.log('🔼 开始隐藏导航栏');
            topNavBar.style.transform = 'translateY(-100%)';
            body.style.paddingTop = '20px';
            if (statusElement) statusElement.textContent = '隐藏';
            console.log('✅ 顶部导航栏已隐藏');
        } else {
            // 显示导航栏
            console.log('🔽 开始显示导航栏');
            topNavBar.style.transform = 'translateY(0)';
            body.style.paddingTop = '70px';
            if (statusElement) statusElement.textContent = '显示';
            console.log('✅ 顶部导航栏已显示');
        }
    } catch (error) {
        console.error('❌ toggleTopNavBar 执行错误:', error);
    }
}

// =====================================
// 多窗口管理系统
// =====================================

class WindowManager {
    constructor() {
        this.windows = new Map(); // 存储所有窗口
        this.activeWindow = null;
        this.zIndexCounter = 1000;
        this.nextZIndex = 15000;
        this.windowCounter = 0;
        this.dragData = null;
        this.resizeData = null; // 添加调整大小数据
        
        this.init();
        this.setupEventListeners();
    }
    
    setupEventListeners() {
        // 页面加载完成后设置事件监听器
        document.addEventListener('DOMContentLoaded', () => {
            // 切换按钮事件监听器
            const toggleBtn = document.getElementById('toggleNavBtn');
            if (toggleBtn) {
                toggleBtn.addEventListener('click', toggleTopNavBar);
                console.log('✅ 切换按钮事件监听器已添加');
            }
            
            // 键盘快捷键支持
            document.addEventListener('keydown', (e) => {
                // Ctrl+Alt+H 或 Cmd+Option+H
                if ((e.ctrlKey || e.metaKey) && e.altKey && e.key.toLowerCase() === 'h') {
                    e.preventDefault();
                    toggleTopNavBar();
                }
                
                // ESC键切换导航栏
                if (e.key === 'Escape') {
                    toggleTopNavBar();
                }
            });
        });
    }
    
    init() {
        // 绑定事件
        document.addEventListener('mousedown', (e) => this.handleGlobalMouseDown(e));
        document.addEventListener('mousemove', (e) => this.handleGlobalMouseMove(e));
        document.addEventListener('mouseup', (e) => this.handleGlobalMouseUp(e));
        
        // 绑定双击事件用于最大化/还原窗口
        document.addEventListener('dblclick', (e) => this.handleDoubleClick(e));
    }
    
    // 处理双击事件
    handleDoubleClick(e) {
        const windowHeader = e.target.closest('.window-header');
        if (windowHeader && !e.target.closest('.window-controls')) {
            const windowElement = windowHeader.closest('.window-container');
            const windowId = windowElement.getAttribute('data-window-id');
            this.toggleMaximizeWindow(windowId);
        }
    }
    
    // 最大化/还原窗口
    toggleMaximizeWindow(windowId) {
        const window = this.windows.get(windowId);
        if (!window) return;
        
        const windowElement = window.element;
        
        if (window.isMaximized) {
            // 还原窗口
            windowElement.style.left = window.originalBounds.left + 'px';
            windowElement.style.top = window.originalBounds.top + 'px';
            windowElement.style.width = window.originalBounds.width + 'px';
            windowElement.style.height = window.originalBounds.height + 'px';
            window.isMaximized = false;
            windowElement.classList.remove('maximized');
        } else {
            // 保存当前位置和大小
            window.originalBounds = {
                left: parseInt(windowElement.style.left),
                top: parseInt(windowElement.style.top),
                width: parseInt(windowElement.style.width),
                height: parseInt(windowElement.style.height)
            };
            
            // 最大化窗口
            windowElement.style.left = '20px';
            windowElement.style.top = '60px'; // 避免覆盖顶部按钮栏
            windowElement.style.width = (window.innerWidth - 40) + 'px';
            windowElement.style.height = (window.innerHeight - 80) + 'px';
            window.isMaximized = true;
            windowElement.classList.add('maximized');
        }
    }
    
    // 创建新窗口
    createWindow(id, title, content, options = {}) {
        const windowId = id || `window_${++this.windowCounter}`;
        
        // 如果窗口已存在，则激活它
        if (this.windows.has(windowId)) {
            this.activateWindow(windowId);
            return windowId;
        }
        
        const defaultOptions = {
            width: 800,
            height: 600,
            x: 100 + (this.windows.size * 30),
            y: 100 + (this.windows.size * 30),
            minimized: false
        };
        
        const windowOptions = { ...defaultOptions, ...options };
        
        // 创建窗口HTML
        const windowElement = this.createWindowElement(windowId, title, content, windowOptions);
        
        // 添加到容器
        const multiModal = document.getElementById('multiModal');
        multiModal.appendChild(windowElement);
        
        // 存储窗口信息
        const windowInfo = {
            id: windowId,
            title,
            element: windowElement,
            options: windowOptions,
            isMinimized: false,
            isMaximized: false,
            originalBounds: null
        };
        
        this.windows.set(windowId, windowInfo);
        
        // 激活新窗口
        this.activateWindow(windowId);
        
        // 更新窗口管理器
        this.updateWindowManager();
        
        return windowId;
    }
    
    // 创建窗口HTML元素
    createWindowElement(windowId, title, content, options) {
        const windowDiv = document.createElement('div');
        windowDiv.className = 'window-container';
        windowDiv.style.cssText = `
            left: ${options.x}px;
            top: ${options.y}px;
            width: ${options.width}px;
            height: ${options.height}px;
            z-index: ${this.nextZIndex++};
        `;
        windowDiv.setAttribute('data-window-id', windowId);
        
        windowDiv.innerHTML = `
            <div class="window-header" data-drag-handle="true">
                <div class="window-title">${title}</div>
                <div class="window-controls">
                    <button class="minimize" onclick="windowManager.minimizeWindow('${windowId}')" title="最小化">−</button>
                    <button class="close" onclick="windowManager.closeWindow('${windowId}')" title="关闭">×</button>
                </div>
            </div>
            <div class="window-content">${content}</div>
            
            <!-- 窗口调整大小手柄 -->
            <div class="window-resize-handle n" data-resize-direction="n"></div>
            <div class="window-resize-handle s" data-resize-direction="s"></div>
            <div class="window-resize-handle w" data-resize-direction="w"></div>
            <div class="window-resize-handle e" data-resize-direction="e"></div>
            <div class="window-resize-handle nw" data-resize-direction="nw"></div>
            <div class="window-resize-handle ne" data-resize-direction="ne"></div>
            <div class="window-resize-handle sw" data-resize-direction="sw"></div>
            <div class="window-resize-handle se" data-resize-direction="se"></div>
        `;
        
        return windowDiv;
    }
    
    // 激活窗口
    activateWindow(windowId) {
        // 取消所有窗口的激活状态
        this.windows.forEach(window => {
            window.element.classList.remove('active');
        });
        
        const window = this.windows.get(windowId);
        if (window && !window.isMinimized) {
            window.element.classList.add('active');
            window.element.style.zIndex = this.nextZIndex++;
            this.activeWindow = windowId;
            this.updateWindowManager();
        }
    }
    
    // 最小化窗口
    minimizeWindow(windowId) {
        const window = this.windows.get(windowId);
        if (window) {
            window.isMinimized = true;
            window.element.classList.add('minimized');
            
            if (this.activeWindow === windowId) {
                this.activeWindow = null;
                // 激活下一个可见窗口
                for (const [id, win] of this.windows) {
                    if (!win.isMinimized) {
                        this.activateWindow(id);
                        break;
                    }
                }
            }
            this.updateWindowManager();
        }
    }
    
    // 恢复窗口
    restoreWindow(windowId) {
        const window = this.windows.get(windowId);
        if (window) {
            window.isMinimized = false;
            window.element.classList.remove('minimized');
            this.activateWindow(windowId);
        }
    }
    
    // 关闭窗口
    closeWindow(windowId) {
        const window = this.windows.get(windowId);
        if (window) {
            window.element.remove();
            this.windows.delete(windowId);
            
            if (this.activeWindow === windowId) {
                this.activeWindow = null;
                // 激活下一个可见窗口
                for (const [id, win] of this.windows) {
                    if (!win.isMinimized) {
                        this.activateWindow(id);
                        break;
                    }
                }
            }
            this.updateWindowManager();
        }
    }
    
    // 更新窗口管理器（任务栏）
    updateWindowManager() {
        const windowList = document.getElementById('windowList');
        windowList.innerHTML = '';
        
        this.windows.forEach((window, windowId) => {
            const windowItem = document.createElement('div');
            windowItem.className = `window-item ${this.activeWindow === windowId ? 'active' : ''}`;
            
            // 简化窗口标题显示
            let displayTitle = window.title.replace('热点编辑器 - ', '');
            if (displayTitle.length > 15) {
                displayTitle = displayTitle.substring(0, 12) + '...';
            }
            
            windowItem.innerHTML = `
                <div class="window-title">${displayTitle}</div>
                <div class="window-controls">
                    ${window.isMinimized ? 
                        `<button class="window-control-btn activate-btn" onclick="windowManager.restoreWindow('${windowId}')" title="恢复">↗</button>` :
                        `<button class="window-control-btn minimize-btn" onclick="windowManager.minimizeWindow('${windowId}')" title="最小化">−</button>`
                    }
                    <button class="window-control-btn close-btn" onclick="windowManager.closeWindow('${windowId}')" title="关闭">×</button>
                </div>
            `;
            
            // 点击窗口项激活窗口
            windowItem.addEventListener('click', (e) => {
                if (!e.target.classList.contains('window-control-btn')) {
                    if (window.isMinimized) {
                        this.restoreWindow(windowId);
                    } else {
                        this.activateWindow(windowId);
                    }
                }
            });
            
            windowList.appendChild(windowItem);
        });
        
        // 任务栏始终显示，只在没有窗口时隐藏标题
        const manager = document.getElementById('windowManager');
        const header = manager.querySelector('.manager-header');
        
        if (this.windows.size === 0) {
            manager.classList.add('minimized');
            header.style.display = 'none';
        } else {
            manager.classList.remove('minimized');
            header.style.display = 'flex';
        }
    }
    
    // 处理拖拽和调整大小
    handleGlobalMouseDown(e) {
        // 检查是否点击了调整大小手柄
        const resizeHandle = e.target.closest('.window-resize-handle');
        if (resizeHandle) {
            const windowElement = resizeHandle.closest('.window-container');
            const windowId = windowElement.getAttribute('data-window-id');
            const direction = resizeHandle.getAttribute('data-resize-direction');
            
            this.activateWindow(windowId);
            
            const rect = windowElement.getBoundingClientRect();
            this.resizeData = {
                windowElement,
                direction,
                startX: e.clientX,
                startY: e.clientY,
                startWidth: rect.width,
                startHeight: rect.height,
                startLeft: parseInt(windowElement.style.left),
                startTop: parseInt(windowElement.style.top)
            };
            
            windowElement.classList.add('resizing');
            e.preventDefault();
            return;
        }
        
        // 处理窗口拖拽
        const windowHeader = e.target.closest('.window-header');
        if (windowHeader && windowHeader.getAttribute('data-drag-handle')) {
            const windowElement = windowHeader.closest('.window-container');
            const windowId = windowElement.getAttribute('data-window-id');
            
            this.activateWindow(windowId);
            
            this.dragData = {
                windowElement,
                startX: e.clientX,
                startY: e.clientY,
                startLeft: parseInt(windowElement.style.left),
                startTop: parseInt(windowElement.style.top)
            };
            
            e.preventDefault();
        }
    }
    
    handleGlobalMouseMove(e) {
        // 处理窗口调整大小
        if (this.resizeData) {
            const deltaX = e.clientX - this.resizeData.startX;
            const deltaY = e.clientY - this.resizeData.startY;
            const direction = this.resizeData.direction;
            
            let newWidth = this.resizeData.startWidth;
            let newHeight = this.resizeData.startHeight;
            let newLeft = this.resizeData.startLeft;
            let newTop = this.resizeData.startTop;
            
            // 根据方向调整尺寸和位置
            if (direction.includes('e')) {
                newWidth = Math.max(400, this.resizeData.startWidth + deltaX);
            }
            if (direction.includes('w')) {
                newWidth = Math.max(400, this.resizeData.startWidth - deltaX);
                newLeft = this.resizeData.startLeft + (this.resizeData.startWidth - newWidth);
            }
            if (direction.includes('s')) {
                newHeight = Math.max(300, this.resizeData.startHeight + deltaY);
            }
            if (direction.includes('n')) {
                newHeight = Math.max(300, this.resizeData.startHeight - deltaY);
                newTop = this.resizeData.startTop + (this.resizeData.startHeight - newHeight);
            }
            
            // 限制最大尺寸
            const maxWidth = window.innerWidth * 0.95;
            const maxHeight = window.innerHeight * 0.95;
            newWidth = Math.min(newWidth, maxWidth);
            newHeight = Math.min(newHeight, maxHeight);
            
            // 应用新的尺寸和位置
            this.resizeData.windowElement.style.width = newWidth + 'px';
            this.resizeData.windowElement.style.height = newHeight + 'px';
            this.resizeData.windowElement.style.left = newLeft + 'px';
            this.resizeData.windowElement.style.top = newTop + 'px';
            
            return;
        }
        
        // 处理窗口拖拽
        if (this.dragData) {
            const deltaX = e.clientX - this.dragData.startX;
            const deltaY = e.clientY - this.dragData.startY;
            
            this.dragData.windowElement.style.left = (this.dragData.startLeft + deltaX) + 'px';
            this.dragData.windowElement.style.top = (this.dragData.startTop + deltaY) + 'px';
        }
    }
    
    handleGlobalMouseUp(e) {
        if (this.resizeData) {
            this.resizeData.windowElement.classList.remove('resizing');
            this.resizeData = null;
        }
        this.dragData = null;
    }
}

// 全局窗口管理器实例
const windowManager = new WindowManager();

// =====================================
// 地图热点展示功能
// =====================================

// 数据持久化管理
class DataManager {
    constructor() {
        this.storageKey = 'map_hotspot_data';
        this.autoSaveInterval = null;
        this.hasUnsavedChanges = false;
        this.init();
    }
    
    async init() {
        await this.loadData();
        this.startAutoSave();
        this.updateSaveStatus();
    }
    
    // 加载数据
    async loadData() {
        try {
            // 首先尝试从localStorage加载
            const savedData = localStorage.getItem(this.storageKey);
            if (savedData) {
                const data = JSON.parse(savedData);
                hotspotInfo = data.hotspotInfo || this.getDefaultHotspotInfo();
                hotspotNames = data.hotspotNames || {};
                imageData = data.imageData || this.getDefaultImageData();
                nextHotspotId = data.nextHotspotId || 20;
                console.log('数据已从localStorage加载');
                
                // 同步数据到页面
                setTimeout(() => {
                    this.syncDataToPage();
                    // 重新初始化事件监听器
                    if (typeof initEventListeners === 'function') {
                        initEventListeners();
                    }
                }, 100);
            } else {
                // 尝试从项目文件加载
                console.log('localStorage中没有数据，尝试从服务器加载...');
                await this.loadFromProjectFile();
            }
        } catch (error) {
            console.error('加载数据失败:', error);
            // 使用默认数据
            hotspotInfo = this.getDefaultHotspotInfo();
            hotspotNames = {};
            imageData = this.getDefaultImageData();
            nextHotspotId = 20;
        }
    }
    
    // 从项目文件加载数据
    async loadFromProjectFile() {
        try {
            console.log('正在从服务器获取最新数据...');
            
            // 尝试从Python服务器加载数据
            const response = await fetch('/load-data');
            const result = await response.json();
            
            if (result.success) {
                const data = result.data;
                hotspotInfo = data.hotspotInfo || this.getDefaultHotspotInfo();
                hotspotNames = data.hotspotNames || {};
                imageData = data.imageData || this.getDefaultImageData();
                nextHotspotId = data.nextHotspotId || 20;
                console.log('✅ 数据已从服务器加载成功');
                console.log(`📊 加载的数据：图片 ${imageData.images.length} 个，热点 ${Object.keys(hotspotInfo).length} 个，自定义名称 ${Object.keys(hotspotNames).length} 个`);
                
                // 将服务器数据保存到localStorage作为备份
                this.saveData();
                
                // 同步数据到页面
                setTimeout(() => {
                    this.syncDataToPage();
                    // 重新初始化事件监听器
                    if (typeof initEventListeners === 'function') {
                        initEventListeners();
                    }
                }, 100);
                
                return true;
            } else {
                // 使用默认数据
                hotspotInfo = this.getDefaultHotspotInfo();
                hotspotNames = {};
                imageData = this.getDefaultImageData();
                nextHotspotId = 20;
                console.log('⚠️ 使用默认数据:', result.message);
                return false;
            }
        } catch (error) {
            console.error('❌ 从服务器加载数据失败:', error);
            // 使用默认数据
            hotspotInfo = this.getDefaultHotspotInfo();
            hotspotNames = {};
            imageData = this.getDefaultImageData();
            nextHotspotId = 20;
            return false;
        }
    }
    
    // 保存数据
    saveData() {
        try {
            const data = {
                hotspotInfo: hotspotInfo,
                hotspotNames: hotspotNames,
                imageData: imageData,
                nextHotspotId: nextHotspotId,
                lastUpdated: new Date().toISOString()
            };
            localStorage.setItem(this.storageKey, JSON.stringify(data));
            this.hasUnsavedChanges = false;
            this.updateSaveStatus();
            console.log('数据已保存到localStorage');
            return true;
        } catch (error) {
            console.error('保存数据失败:', error);
            return false;
        }
    }
    
    // 标记数据已更改
    markDataChanged() {
        this.hasUnsavedChanges = true;
        this.updateSaveStatus();
    }
    
    // 更新保存状态显示
    updateSaveStatus() {
        const statusElement = document.getElementById('saveStatus');
        if (statusElement) {
            if (this.hasUnsavedChanges) {
                statusElement.textContent = offlineMode ? '离线未保存' : '未保存';
                statusElement.style.color = '#dc3545';
                statusElement.style.fontWeight = 'bold';
            } else {
                statusElement.textContent = offlineMode ? '离线已保存' : '已保存';
                statusElement.style.color = offlineMode ? '#ffc107' : '#28a745';
                statusElement.style.fontWeight = 'normal';
            }
        }
    }
    
    // 同步数据到页面
    syncDataToPage() {
        console.log('开始同步数据到页面...');
        
        // 遍历所有图片数据
        imageData.images.forEach(image => {
            let imageContainer = document.querySelector(`[data-image-id="${image.id}"]`);
            
            // 如果图片容器不存在，创建新的容器
            if (!imageContainer) {
                console.log('创建新的图片容器:', image.id, image.src);
                imageContainer = this.createImageContainer(image);
            }
            
            if (imageContainer) {
                const map = imageContainer.querySelector('map');
                const overlay = imageContainer.querySelector('.hotspot-overlay');
                
                // 清空现有的热点
                overlay.innerHTML = '';
                map.innerHTML = '';
                
                // 重新添加热点
                image.hotspots.forEach(hotspot => {
                    // 添加area标签
                    const area = document.createElement('area');
                    area.setAttribute('shape', 'rect');
                    area.setAttribute('coords', hotspot.coords);
                    area.setAttribute('href', hotspot.href);
                    map.appendChild(area);
                    
                    // 添加热点可视化区域
                    const coords = hotspot.coords.split(',');
                    const left = coords[0];
                    const top = coords[1];
                    const width = coords[2] - coords[0];
                    const height = coords[3] - coords[1];
                    
                    const hotspotArea = document.createElement('div');
                    hotspotArea.className = 'hotspot-area';
                    hotspotArea.setAttribute('data-href', hotspot.href);
                    hotspotArea.style.left = `${left}px`;
                    hotspotArea.style.top = `${top}px`;
                    hotspotArea.style.width = `${width}px`;
                    hotspotArea.style.height = `${height}px`;
                    overlay.appendChild(hotspotArea);
                });
            }
        });
        
        // 清理不存在的图片容器
        const existingContainers = document.querySelectorAll('.image-container');
        existingContainers.forEach(container => {
            const imageId = parseInt(container.getAttribute('data-image-id'));
            const imageExists = imageData.images.some(img => img.id === imageId);
            if (!imageExists) {
                console.log('删除不存在的图片容器:', imageId);
                container.remove();
            }
        });
        
        console.log('数据同步完成');
    }
    
    // 创建图片容器
    createImageContainer(imageData) {
        const container = document.querySelector('.container');
        const imageContainer = document.createElement('div');
        imageContainer.className = 'image-container';
        imageContainer.setAttribute('data-image-id', imageData.id);
        
        // 添加删除按钮
        const deleteBtn = document.createElement('div');
        deleteBtn.className = 'image-delete-btn';
        deleteBtn.innerHTML = '×';
        deleteBtn.title = '删除图片';
        deleteBtn.onclick = function() { deleteImage(imageData.id); };
        
        // 创建图片元素
        const img = document.createElement('img');
        img.border = '0';
        img.setAttribute('usemap', `#Map${imageData.id}`);
        img.src = imageData.src;
        
        // 如果有宽高信息，设置图片尺寸
        if (imageData.width) img.width = imageData.width;
        if (imageData.height) img.height = imageData.height;
        
        // 创建map元素
        const map = document.createElement('map');
        map.name = `Map${imageData.id}`;
        map.id = `Map${imageData.id}`;
        
        // 创建热点可视化层
        const overlay = document.createElement('div');
        overlay.className = 'hotspot-overlay';
        
        // 组装容器
        imageContainer.appendChild(deleteBtn);
        imageContainer.appendChild(img);
        imageContainer.appendChild(map);
        imageContainer.appendChild(overlay);
        
        // 添加到页面（新图片显示在最前面）
        const firstImageContainer = container.querySelector('.image-container');
        if (firstImageContainer) {
            container.insertBefore(imageContainer, firstImageContainer);
        } else {
            container.appendChild(imageContainer);
        }
        
        return imageContainer;
    }
    
    // 开始自动保存
    startAutoSave() {
        this.autoSaveInterval = setInterval(() => {
            if (this.hasUnsavedChanges) {
                this.saveData();
            }
        }, 30000); // 每30秒自动保存一次
    }
    
    // 停止自动保存
    stopAutoSave() {
        if (this.autoSaveInterval) {
            clearInterval(this.autoSaveInterval);
            this.autoSaveInterval = null;
        }
    }
    
    // 获取默认热点信息
    getDefaultHotspotInfo() {
        return {
            '#1': '选择方案配置模式\nselect[title="选择方案配置模式"]',
            '#2': '产品选择区域\n#product-8-1 .text-center',
            '#3': '创建订单按钮\nbutton[onClick="handleCreateOrder"]',
            '#4': '文件路径： app/components/tooltips/ProductBreakdownTooltip.tsx\n唯一定位名： .bg-gray-800.text-white.rounded-lg.z-[9999]',
            '#5': '文件路径： app/clients/CreateOrderModal.tsx\n唯一定位名： .bg-green-50.border-green-200',
            '#6': '文件路径： app/clients/CreateOrderModal.tsx\n唯一定位名： select[value*="scheme"] 或 select option[value="scheme"]',
            '#7': '文件路径： app/clients/CreateOrderModal.tsx\n唯一定位名： select[value*="schemeId"] 或 .space-y-1 select',
            '#8': '文件路径： app/clients/CreateOrderModal.tsx\n唯一定位名： input[type="number"].flex-1.text-center',
            '#9': '文件路径： app/clients/CreateOrderModal.tsx\n唯一定位名： .bg-gray-50.rounded.p-2 .text-xs.space-y-1',
            '#10': '订单详情头部的左侧区域（包含订单标题）\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： .bg-gradient-to-r.from-indigo-50.to-purple-50 .flex.items-center.justify-between.mb-3 > div:first-child',
            '#11': '订单详情头部的统计卡片网格区域（原价、折扣、实付金额）\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： .grid.grid-cols-1.md\\:grid-cols-3.gap-4',
            '#12': '开始使用时间区域的第一个子元素\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： .bg-white\\/70.rounded-lg .grid > div:first-child',
            '#13': '开始使用时间区域的第二个子元素\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： .bg-white\\/70.rounded-lg .grid > div:nth-child(2)',
            '#14': '方案产品网格中第四个产品的价格信息区域\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： .grid-cols-7 > div:nth-child(4) .flex.items-center.justify-between',
            '#15': '方案产品网格中第四个产品的进度条\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： .grid-cols-7 > div:nth-child(4) .bg-gray-200.rounded-full.h-1\\.5',
            '#16': '新热点区域16\n具体信息待补充',
            '#17': '新热点区域17\n具体信息待补充',
            '#18': '新热点区域18\n具体信息待补充',
            '#19': '方案产品网格中第四个产品的ProductBreakdownTooltip组件\n文件路径： app/clients/ClientOrderDetailModal.tsx\n唯一定位名： ProductBreakdownTooltip .relative.inline-block.group\n这是ProductBreakdownTooltip组件渲染的悬浮提示触发器，具有relative inline-block group ml-1的类名组合，当鼠标悬停时会显示产品详情的黑色悬浮框。'
        };
    }
    
    // 获取默认图片数据
    getDefaultImageData() {
        return {
            images: [
                {
                    id: 1,
                    src: "IMG/1.png",
                    width: null,
                    height: null,
                    hotspots: [
                        { id: 1, coords: "830,133,1032,236", href: "#1" },
                        { id: 2, coords: "1282,370,1437,634", href: "#2" },
                        { id: 3, coords: "1294,1154,1462,1186", href: "#3" }
                    ]
                },
                {
                    id: 2,
                    src: "IMG/wechat_2025-09-01_153533_589.png",
                    width: null,
                    height: null,
                    hotspots: [
                        { id: 4, coords: "412,327,708,429", href: "#4" }
                    ]
                },
                // 图片ID 3已移除，因为文件IMG/3.png不存在
                // {
                //     id: 3,
                //     src: "IMG/3.png",
                //     width: 403,
                //     height: 603,
                //     hotspots: [
                //         { id: 5, coords: "14,112,375,181", href: "#5" },
                //         { id: 6, coords: "20,228,384,261", href: "#6" },
                //         { id: 7, coords: "19,288,387,328", href: "#7" },
                //         { id: 8, coords: "14,369,367,408", href: "#8" },
                //         { id: 9, coords: "21,424,185,533", href: "#9" }
                //     ]
                // },
                {
                    id: 4,
                    src: "IMG/4.png",
                    width: 1625,
                    height: 1134,
                    hotspots: [
                        { id: 10, coords: "1350,136,1559,193", href: "#10" },
                        { id: 11, coords: "241,119,1584,317", href: "#11" },
                        { id: 12, coords: "251,327,597,400", href: "#12" },
                        { id: 13, coords: "886,331,1456,394", href: "#13" },
                        { id: 14, coords: "828,812,1002,835", href: "#14" },
                        { id: 15, coords: "828,838,1005,854", href: "#15" },
                        { id: 16, coords: "958,794,998,812", href: "#16" },
                        { id: 17, coords: "1437,1049,1585,1097", href: "#17" },
                        { id: 18, coords: "1264,1049,1420,1100", href: "#18" }
                    ]
                },
                {
                    id: 5,
                    src: "IMG/5.png",
                    width: 720,
                    height: 740,
                    hotspots: [
                        { id: 19, coords: "109,73,509,566", href: "#19" }
                    ]
                }
            ]
        };
    }
}

// 初始化数据管理器
let dataManager = null;

// 全局变量
let isDrawingMode = false;
let isSelectionMode = true; // 默认为选择模式
let isContinuousDrawMode = false; // Ctrl键连续绘画模式
let currentDrawingImage = null;
let drawingStartPoint = null;
let serverOnline = false;
let offlineMode = false;
let isMovingHotspot = false;
let currentMovingHotspot = null;
let moveStartPoint = null;
let dragOffset = { x: 0, y: 0 }; // 记录拖动时的偏移量

// 全局数据变量（将由DataManager初始化）
let imageData = null;
let hotspotInfo = null;
let hotspotNames = {}; // 存储热点自定义名称：{hotspotId: '自定义名称'}
let nextHotspotId = 20;

// 操作日志系统
let operationLogs = [];
let maxLogEntries = 1000; // 最大日志条数
let logId = 1;

/**
 * 操作日志管理器
 */
class OperationLogger {
    constructor() {
        this.logs = operationLogs;
        this.maxEntries = maxLogEntries;
        this.currentId = logId;
        this.loadFromLocalStorage();
    }

    /**
     * 记录操作日志
     * @param {string} action - 操作类型 (create, update, delete, move, batch_delete, etc.)
     * @param {string} target - 操作目标 (hotspot, image, data)
     * @param {object} details - 操作详情
     * @param {object} beforeState - 操作前状态（用于撤销）
     * @param {object} afterState - 操作后状态
     */
    log(action, target, details = {}, beforeState = null, afterState = null) {
        const logEntry = {
            id: this.currentId++,
            timestamp: new Date().toISOString(),
            action: action,
            target: target,
            details: details,
            beforeState: beforeState,
            afterState: afterState,
            user: 'local', // 未来可能支持多用户
            level: details.level || 'info' // info, warning, error, debug
        };

        this.logs.unshift(logEntry); // 新日志在前面

        // 限制日志数量
        if (this.logs.length > this.maxEntries) {
            this.logs.splice(this.maxEntries);
        }

        // 保存到localStorage
        this.saveToLocalStorage();

        // 控制台输出（用于调试）
        this.outputToConsole(logEntry);

        return logEntry;
    }

    /**
     * 输出到控制台
     */
    outputToConsole(logEntry) {
        const timeStr = new Date(logEntry.timestamp).toLocaleTimeString();
        const prefix = `[${timeStr}] [${logEntry.action.toUpperCase()}]`;
        
        switch (logEntry.level) {
            case 'error':
                console.error(prefix, logEntry.details.message || logEntry.details, logEntry);
                break;
            case 'warning':
                console.warn(prefix, logEntry.details.message || logEntry.details, logEntry);
                break;
            case 'debug':
                console.debug(prefix, logEntry.details.message || logEntry.details, logEntry);
                break;
            default:
                console.log(prefix, logEntry.details.message || logEntry.details, logEntry);
        }
    }

    /**
     * 获取日志
     */
    getLogs(filters = {}) {
        let filteredLogs = this.logs;

        if (filters.action) {
            filteredLogs = filteredLogs.filter(log => log.action === filters.action);
        }

        if (filters.target) {
            filteredLogs = filteredLogs.filter(log => log.target === filters.target);
        }

        if (filters.level) {
            filteredLogs = filteredLogs.filter(log => log.level === filters.level);
        }

        if (filters.limit) {
            filteredLogs = filteredLogs.slice(0, filters.limit);
        }

        return filteredLogs;
    }

    /**
     * 清除日志
     */
    clearLogs() {
        this.logs.length = 0;
        this.saveToLocalStorage();
        console.log('操作日志已清除');
    }

    /**
     * 保存到localStorage
     */
    saveToLocalStorage() {
        try {
            localStorage.setItem('map_operation_logs', JSON.stringify({
                logs: this.logs,
                currentId: this.currentId
            }));
        } catch (error) {
            console.error('保存操作日志失败:', error);
        }
    }

    /**
     * 从localStorage加载
     */
    loadFromLocalStorage() {
        try {
            const saved = localStorage.getItem('map_operation_logs');
            if (saved) {
                const data = JSON.parse(saved);
                this.logs = data.logs || [];
                this.currentId = data.currentId || 1;
                operationLogs = this.logs;
                logId = this.currentId;
                console.log(`已加载 ${this.logs.length} 条操作日志`);
            }
        } catch (error) {
            console.error('加载操作日志失败:', error);
            this.logs = [];
            this.currentId = 1;
        }
    }

    /**
     * 导出日志
     */
    exportLogs() {
        const dataStr = JSON.stringify(this.logs, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        const url = URL.createObjectURL(dataBlob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `operation_logs_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
        URL.revokeObjectURL(url);
    }
}

// 初始化操作日志管理器
const logger = new OperationLogger();

/**
 * 显示操作日志查看器
 */
function showOperationLogs() {
    const logs = logger.getLogs({ limit: 100 }); // 最近100条日志
    
    let content = `
        <div style="max-height: 400px; overflow-y: auto;">
            <div style="margin-bottom: 15px; display: flex; gap: 10px; flex-wrap: wrap;">
                <button onclick="filterLogs('all')" class="log-filter-btn" data-filter="all">全部</button>
                <button onclick="filterLogs('create')" class="log-filter-btn" data-filter="create">创建</button>
                <button onclick="filterLogs('delete')" class="log-filter-btn" data-filter="delete">删除</button>
                <button onclick="filterLogs('move')" class="log-filter-btn" data-filter="move">移动</button>
                <button onclick="filterLogs('batch_delete')" class="log-filter-btn" data-filter="batch_delete">批量删除</button>
                <button onclick="filterLogs('error')" class="log-filter-btn" data-filter="error">错误</button>
                <button onclick="logger.clearLogs(); showOperationLogs();" style="background: #dc3545; color: white; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer;">清除日志</button>
                <button onclick="logger.exportLogs();" style="background: #28a745; color: white; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer;">导出日志</button>
            </div>
            <div id="logsList">
    `;
    
    if (logs.length === 0) {
        content += '<p style="text-align: center; color: #666;">暂无操作日志</p>';
    } else {
        logs.forEach(log => {
            const time = new Date(log.timestamp).toLocaleString();
            const levelClass = getLevelClass(log.level);
            const actionIcon = getActionIcon(log.action);
            
            content += `
                <div class="log-entry ${levelClass}" data-action="${log.action}" data-level="${log.level}">
                    <div class="log-header">
                        <span class="log-icon">${actionIcon}</span>
                        <span class="log-action">${log.action.toUpperCase()}</span>
                        <span class="log-target">${log.target}</span>
                        <span class="log-time">${time}</span>
                    </div>
                    <div class="log-message">${log.details.message || JSON.stringify(log.details)}</div>
                    ${log.details.href ? `<div class="log-detail">热点: ${log.details.href}</div>` : ''}
                    ${log.details.error ? `<div class="log-error">错误: ${log.details.error}</div>` : ''}
                </div>
            `;
        });
    }
    
    content += `
            </div>
        </div>
        <style>
            .log-filter-btn {
                padding: 5px 10px;
                border: 1px solid #dee2e6;
                background: #f8f9fa;
                border-radius: 3px;
                cursor: pointer;
                font-size: 12px;
            }
            .log-filter-btn.active {
                background: #007bff;
                color: white;
                border-color: #007bff;
            }
            .log-entry {
                margin-bottom: 10px;
                padding: 10px;
                border-left: 4px solid #dee2e6;
                background: #f8f9fa;
                border-radius: 4px;
                font-size: 12px;
            }
            .log-entry.info { border-left-color: #17a2b8; }
            .log-entry.warning { border-left-color: #ffc107; }
            .log-entry.error { border-left-color: #dc3545; }
            .log-entry.debug { border-left-color: #6c757d; }
            .log-header {
                display: flex;
                gap: 10px;
                align-items: center;
                margin-bottom: 5px;
                font-weight: bold;
            }
            .log-icon { font-size: 14px; }
            .log-action { color: #495057; }
            .log-target { color: #6c757d; font-size: 11px; }
            .log-time { margin-left: auto; color: #6c757d; font-size: 11px; }
            .log-message { margin-bottom: 5px; }
            .log-detail { color: #6c757d; font-size: 11px; }
            .log-error { color: #dc3545; font-size: 11px; }
        </style>
    `;
    
    showCustomModal('操作日志', content, 'info', [
        {
            text: '关闭',
            onclick: () => closeCustomModal()
        }
    ]);
    
    // 设置默认过滤器为激活状态
    const allBtn = document.querySelector('.log-filter-btn[data-filter="all"]');
    if (allBtn) allBtn.classList.add('active');
}

/**
 * 过滤日志
 */
function filterLogs(filter) {
    // 更新按钮状态
    document.querySelectorAll('.log-filter-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-filter="${filter}"]`).classList.add('active');
    
    // 过滤日志条目
    const entries = document.querySelectorAll('.log-entry');
    entries.forEach(entry => {
        if (filter === 'all') {
            entry.style.display = 'block';
        } else if (filter === 'error') {
            entry.style.display = entry.dataset.level === 'error' ? 'block' : 'none';
        } else {
            entry.style.display = entry.dataset.action === filter ? 'block' : 'none';
        }
    });
}

/**
 * 获取日志级别的CSS类
 */
function getLevelClass(level) {
    return level || 'info';
}

/**
 * 获取操作图标
 */
function getActionIcon(action) {
    const icons = {
        'create': '✨',
        'delete': '🗑️',
        'move': '🔄',
        'batch_delete': '🗂️',
        'update': '✏️',
        'error': '❌',
        'warning': '⚠️'
    };
    return icons[action] || '📝';
}

/**
 * 测试选中样式 - 调试用
 */
function testSelectionStyle() {
    const allHotspots = document.querySelectorAll('.hotspot-area');
    console.log(`找到 ${allHotspots.length} 个热点区域`);
    
    if (allHotspots.length > 0) {
        const firstHotspot = allHotspots[0];
        const href = firstHotspot.getAttribute('data-href');
        console.log(`测试选中热点: ${href}`);
        
        // 清除之前的选择
        clearSelection();
        
        // 选中第一个热点
        selectHotspot(href);
        
        // 检查样式是否应用
        setTimeout(() => {
            const computedStyle = window.getComputedStyle(firstHotspot);
            console.log('热点元素computed style:', {
                background: computedStyle.background,
                border: computedStyle.border,
                boxShadow: computedStyle.boxShadow,
                animation: computedStyle.animation,
                zIndex: computedStyle.zIndex
            });
        }, 100);
        
        showInfo(`已测试选中热点 ${href}\n请查看控制台了解样式详情`);
    } else {
        showWarning('未找到任何热点区域');
    }
}

/**
 * 选中功能调试 - 新增
 */
function testSelectionDebug() {
    console.log('🔧 开始选中功能调试...');
    
    const allHotspots = document.querySelectorAll('.hotspot-area');
    console.log(`📊 找到 ${allHotspots.length} 个热点区域`);
    
    if (allHotspots.length === 0) {
        showWarning('❌ 未找到任何热点区域！');
        return;
    }
    
    // 清除现有选择
    clearSelection();
    
    // 选择前3个热点进行测试
    const testCount = Math.min(3, allHotspots.length);
    const testHotspots = Array.from(allHotspots).slice(0, testCount);
    
    console.log(`🎯 测试选中前 ${testCount} 个热点...`);
    
    testHotspots.forEach((hotspot, index) => {
        const href = hotspot.getAttribute('data-href');
        console.log(`${index + 1}. 选中热点: ${href}`);
        selectHotspot(href);
    });
    
    // 延迟检查样式应用情况
    setTimeout(() => {
        console.log(`🎨 样式应用检查结果:`);
        testHotspots.forEach((hotspot, index) => {
            const href = hotspot.getAttribute('data-href');
            const hasClass = hotspot.classList.contains('selected-hotspot');
            const computedStyle = window.getComputedStyle(hotspot);
            const isVisible = computedStyle.backgroundColor !== 'rgba(0, 0, 0, 0)';
            
            console.log(`${index + 1}. 热点 ${href}:`, {
                hasSelectedClass: hasClass,
                backgroundVisible: isVisible,
                backgroundColor: computedStyle.backgroundColor,
                borderColor: computedStyle.borderColor,
                borderWidth: computedStyle.borderWidth
            });
        });
        
        showInfo(`🎯 选中测试完成！\n\n已选中 ${selectedHotspots.size} 个热点\n请查看控制台了解详细信息\n\n如果看不到橙色边框，说明样式有问题`, 6000);
    }, 200);
}

/**
 * 强制显示所有选中热点 - 终极调试工具
 */
function forceShowSelected() {
    console.log('🔥 强制显示所有选中热点...');
    
    if (selectedHotspots.size === 0) {
        showWarning('当前没有选中的热点！\n请先框选或点击"🎯 测试选中"按钮');
        return;
    }
    
    selectedHotspots.forEach(href => {
        const hotspotArea = document.querySelector(`[data-href="${href}"]`);
        if (hotspotArea) {
            // 强制设置最明显的样式
            hotspotArea.style.background = 'rgba(255, 0, 0, 0.8)';  // 红色背景
            hotspotArea.style.border = '8px solid red';  // 红色粗边框
            hotspotArea.style.boxShadow = '0 0 30px red';  // 红色发光
            hotspotArea.style.zIndex = '9999';  // 最高层级
            hotspotArea.style.transform = 'scale(1.2)';  // 明显缩放
            hotspotArea.style.animation = 'none';  // 移除动画避免冲突
            
            console.log(`🔥 强制设置热点 ${href} 为红色高亮`);
        }
    });
    
    showSuccess(`🔥 已强制设置 ${selectedHotspots.size} 个选中热点为红色高亮！\n\n如果现在还看不到，说明DOM结构有问题`, 4000);
}

// 当前选中的热点
let currentHotspot = null;

// 图片管理功能
function showAddImageModal() {
    document.getElementById('addImageModal').style.display = 'block';
    // 初始化剪贴板上传功能
    initClipboardUpload();
    // 重置预览区域
    resetImagePreview();
}

function closeAddImageModal() {
    document.getElementById('addImageModal').style.display = 'none';
    // 清理预览
    resetImagePreview();
    // 清理剪贴板事件监听器
    cleanupClipboardUpload();
}

// 重置图片预览
function resetImagePreview() {
    const previewContainer = document.getElementById('imagePreviewContainer');
    const preview = document.getElementById('imagePreview');
    const uploadArea = document.getElementById('clipboardUploadArea');
    
    // 隐藏预览区域
    previewContainer.style.display = 'none';
    previewContainer.classList.remove('show');
    
    // 清空预览图片
    preview.src = '';
    
    // 重置上传区域
    uploadArea.innerHTML = `
        <div class="upload-icon">📋</div>
        <p><strong>从剪贴板上传图片</strong></p>
        <p>复制图片后，点击此区域或按 Ctrl+V 粘贴</p>
        <p style="font-size: 12px; color: #666;">支持截图、复制的图片等</p>
    `;
    uploadArea.style.borderColor = '#007bff';
    uploadArea.style.background = '#f8f9fa';
    uploadArea.style.padding = '20px';
    
    // 清空文件输入
    document.getElementById('imageFile').value = '';
    document.getElementById('imageName').value = '';
    
    // 清理文件引用
    window.clipboardImageFile = null;
    window.selectedImageFile = null;
}

// 处理文件选择
function handleFileSelect() {
    const fileInput = document.getElementById('imageFile');
    const file = fileInput.files[0];
    
    if (file && file.type.startsWith('image/')) {
        // 自动设置文件名
        const nameInput = document.getElementById('imageName');
        const timestamp = Date.now();
        const extension = file.name.split('.').pop() || 'png';
        const fileName = `IMG/clipboard_${timestamp}.${extension}`;
        nameInput.value = fileName;
        
        // 在剪贴板上传区域直接显示图片预览
        showImagePreviewInUploadArea(file, fileName);
        
        // 清除剪贴板文件引用，使用文件选择器的文件
        window.clipboardImageFile = null;
        window.selectedImageFile = file;
    }
}

// 显示图片预览
function showImagePreview(file) {
    const previewContainer = document.getElementById('imagePreviewContainer');
    const preview = document.getElementById('imagePreview');
    const previewName = document.getElementById('previewImageName');
    const previewSize = document.getElementById('previewImageSize');
    const previewDimensions = document.getElementById('previewImageDimensions');
    
    // 创建文件读取器
    const reader = new FileReader();
    reader.onload = function(e) {
        // 设置预览图片
        preview.src = e.target.result;
        
        // 显示预览容器
        previewContainer.style.display = 'block';
        previewContainer.classList.add('show');
        
        // 设置图片信息
        previewName.textContent = `文件名：${file.name}`;
        previewSize.textContent = `文件大小：${formatFileSize(file.size)}`;
        
        // 获取图片尺寸
        const img = new Image();
        img.onload = function() {
            previewDimensions.textContent = `尺寸：${img.width} × ${img.height} 像素`;
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 删除图片功能
async function deleteImage(imageId) {
    // 只有在编辑模式下才允许删除图片
    if (!isDrawingMode) {
        return;
    }
    
    showConfirm(`确定要删除图片 ${imageId} 吗？\n\n删除图片将同时删除该图片上的所有热点！`, async () => {
        console.log('删除图片:', imageId);
        
        // 找到对应的图片容器
        const imageContainer = document.querySelector(`[data-image-id="${imageId}"]`);
        if (!imageContainer) {
            showError('找不到指定的图片！');
            return;
        }
        
        // 获取该图片上的所有热点
        const hotspots = imageContainer.querySelectorAll('.hotspot-area');
        const hotspotHrefs = Array.from(hotspots).map(hotspot => hotspot.getAttribute('data-href'));
        
        console.log('要删除的热点:', hotspotHrefs);
        
        try {
            // 如果服务器在线，使用API删除
            if (serverOnline) {
                const response = await fetch(`/delete-image/${imageId}`, {
                    method: 'DELETE'
                });
                const result = await response.json();
                
                if (result.success) {
                    console.log('服务器删除成功:', result.message);
                } else {
                    console.warn('服务器删除失败:', result.message);
                }
            }
            
            // 从本地数据中删除热点信息
            hotspotHrefs.forEach(href => {
                delete hotspotInfo[href];
                console.log('从hotspotInfo中删除:', href);
            });
            
            // 从imageData中删除图片及其热点
            const imageIndex = imageData.images.findIndex(img => img.id === imageId);
            if (imageIndex !== -1) {
                // 删除图片数据
                imageData.images.splice(imageIndex, 1);
                console.log('从imageData中删除图片:', imageId);
            }
            
            // 标记数据已更改
            if (dataManager) {
                dataManager.markDataChanged();
            }
            
            // 从页面中删除图片容器（这会自动删除所有相关的DOM元素）
            imageContainer.remove();
            
            // 确保清理所有相关的area标签
            hotspotHrefs.forEach(href => {
                const area = document.querySelector(`area[href="${href}"]`);
                if (area) {
                    area.remove();
                    console.log('清理area标签:', href);
                }
            });
            
            // 清理可能残留的热点区域
            hotspotHrefs.forEach(href => {
                const hotspotArea = document.querySelector(`[data-href="${href}"]`);
                if (hotspotArea) {
                    hotspotArea.remove();
                    console.log('清理残留热点区域:', href);
                }
            });
            
            // 重新同步数据到页面，确保数据一致性
            if (dataManager) {
                dataManager.syncDataToPage();
                // 重新初始化事件监听器
                if (typeof initEventListeners === 'function') {
                    initEventListeners();
                }
            }
            
            showSuccess(`图片 ${imageId} 已删除！\n删除了 ${hotspotHrefs.length} 个热点。`);
            
        } catch (error) {
            console.error('删除图片失败:', error);
            showError('删除图片时发生错误，但本地数据已更新。');
        }
    });
}

// 剪贴板上传功能
function initClipboardUpload() {
    const uploadArea = document.getElementById('clipboardUploadArea');
    
    // 点击上传区域
    uploadArea.addEventListener('click', handleClipboardPaste);
    
    // 粘贴事件
    document.addEventListener('paste', handleClipboardPaste);
    
    // 拖拽效果
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        handleFileDrop(e.dataTransfer.files);
    });
}

function cleanupClipboardUpload() {
    const uploadArea = document.getElementById('clipboardUploadArea');
    uploadArea.removeEventListener('click', handleClipboardPaste);
    document.removeEventListener('paste', handleClipboardPaste);
}

function handleClipboardPaste(e) {
    const items = (e.clipboardData || e.originalEvent.clipboardData).items;
    
    for (let item of items) {
        if (item.type.indexOf('image') !== -1) {
            const blob = item.getAsFile();
            handleImageFile(blob);
            return;
        }
    }
    
    showWarning('剪贴板中没有找到图片！请先复制一张图片。');
}

function handleFileDrop(files) {
    if (files.length > 0) {
        const file = files[0];
        if (file.type.startsWith('image/')) {
            handleImageFile(file);
        } else {
            showWarning('请选择图片文件！');
        }
    }
}

function handleImageFile(file) {
    // 生成唯一的文件名
    const timestamp = Date.now();
    const extension = file.name.split('.').pop() || 'png';
    const fileName = `IMG/clipboard_${timestamp}.${extension}`;
    
    // 设置文件名到输入框
    document.getElementById('imageName').value = fileName;
    
    // 在剪贴板上传区域直接显示图片预览
    showImagePreviewInUploadArea(file, fileName);
    
    // 存储文件对象供后续使用
    window.clipboardImageFile = file;
}

// 在剪贴板上传区域显示图片预览
function showImagePreviewInUploadArea(file, fileName) {
    const uploadArea = document.getElementById('clipboardUploadArea');
    
    // 创建文件读取器
    const reader = new FileReader();
    reader.onload = function(e) {
        // 创建图片元素
        const img = new Image();
        img.onload = function() {
            // 计算合适的显示尺寸
            const maxWidth = 300;
            const maxHeight = 200;
            let displayWidth = img.width;
            let displayHeight = img.height;
            
            if (displayWidth > maxWidth) {
                displayHeight = (displayHeight * maxWidth) / displayWidth;
                displayWidth = maxWidth;
            }
            if (displayHeight > maxHeight) {
                displayWidth = (displayWidth * maxHeight) / displayHeight;
                displayHeight = maxHeight;
            }
            
            // 更新上传区域内容，直接显示图片
            uploadArea.innerHTML = `
                <div style="position: relative;">
                    <img src="${e.target.result}" style="
                        max-width: ${displayWidth}px; 
                        max-height: ${displayHeight}px; 
                        border-radius: 8px; 
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                        border: 2px solid #fff;
                        object-fit: contain;
                        background: #fff;
                    " alt="图片预览" />
                    <div style="position: absolute; top: -8px; right: -8px; width: 24px; height: 24px; background: #28a745; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: bold;">✓</div>
                </div>
                <div style="margin-top: 10px;">
                    <p style="margin: 5px 0; font-weight: 600; color: #28a745;"><strong>图片已准备就绪</strong></p>
                    <p style="margin: 5px 0; font-size: 12px; color: #495057;">文件名：${fileName}</p>
                    <p style="margin: 5px 0; font-size: 12px; color: #6c757d;">尺寸：${img.width} × ${img.height} 像素</p>
                    <p style="margin: 5px 0; font-size: 12px; color: #6c757d;">大小：${formatFileSize(file.size)}</p>
                    <p style="margin: 5px 0; font-size: 12px; color: #666;">点击"添加图片"按钮完成上传</p>
                </div>
            `;
            uploadArea.style.borderColor = '#28a745';
            uploadArea.style.background = '#f8f9fa';
            uploadArea.style.padding = '15px';
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

async function addNewImage() {
    const fileInput = document.getElementById('imageFile');
    const nameInput = document.getElementById('imageName');
    
    let file = null;
    let imageName = '';
    
    // 检查是否有图片文件
    if (window.clipboardImageFile) {
        // 从剪贴板粘贴的图片
        file = window.clipboardImageFile;
    } else if (window.selectedImageFile) {
        // 从文件选择器选择的图片
        file = window.selectedImageFile;
    } else if (fileInput.files[0]) {
        // 兼容旧的文件选择方式
        file = fileInput.files[0];
    } else {
        showWarning('请选择图片文件或从剪贴板粘贴图片');
        return;
    }
    
    imageName = nameInput.value.trim();
    if (!imageName) {
        showWarning('请输入图片名称');
        return;
    }
    
    // 检查是否离线模式
    if (offlineMode) {
        showWarning('当前处于离线模式！\n\n图片将保存到浏览器本地存储，但不会保存到IMG文件夹。\n服务器恢复后，请重新上传图片。');
        
        // 创建新的图片数据（仅本地）
        const newImage = {
            id: Math.max(...imageData.images.map(img => img.id), 0) + 1,
            src: imageName,
            width: null,
            height: null,
            hotspots: []
        };
        
        imageData.images.unshift(newImage);
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 创建图片容器并添加到页面
        createImageContainer(newImage, file);
        
        // 重新同步数据到页面，确保数据一致性
        if (dataManager) {
            dataManager.syncDataToPage();
            // 重新初始化事件监听器
            if (typeof initEventListeners === 'function') {
                initEventListeners();
            }
        }
        
        // 清理文件引用
        window.clipboardImageFile = null;
        window.selectedImageFile = null;
        
        closeAddImageModal();
        showSuccess('图片添加成功！（离线模式）');
        return;
    }
    
    // 上传图片到服务器
    const uploadSuccess = await uploadImageToServer(file, imageName);
    
    if (uploadSuccess) {
        // 创建新的图片数据
        const newImage = {
            id: Math.max(...imageData.images.map(img => img.id), 0) + 1,
            src: imageName,
            width: null,
            height: null,
            hotspots: []
        };
        
        imageData.images.unshift(newImage);
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 创建图片容器并添加到页面
        createImageContainer(newImage, file);
        
        // 重新同步数据到页面，确保数据一致性
        if (dataManager) {
            dataManager.syncDataToPage();
            // 重新初始化事件监听器
            if (typeof initEventListeners === 'function') {
                initEventListeners();
            }
        }
        
        // 清理文件引用
        window.clipboardImageFile = null;
        window.selectedImageFile = null;
        
        closeAddImageModal();
        showSuccess('图片添加成功！已保存到IMG文件夹。');
    } else {
        showError('图片上传失败！请检查服务器是否运行。');
    }
}

// 上传图片到服务器
async function uploadImageToServer(file, filename) {
    try {
        // 将文件转换为base64
        const base64Data = await fileToBase64(file);
        
        // 发送到服务器
        const response = await fetch('/upload-image', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                imageData: base64Data,
                filename: filename
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            console.log('图片上传成功:', result.message);
            return true;
        } else {
            console.error('图片上传失败:', result.message);
            return false;
        }
    } catch (error) {
        console.error('图片上传失败:', error);
        return false;
    }
}

// 将文件转换为base64
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

function createImageContainer(imageData, file = null) {
    const container = document.querySelector('.container');
    const imageContainer = document.createElement('div');
    imageContainer.className = 'image-container';
    imageContainer.setAttribute('data-image-id', imageData.id);
    
    // 添加删除按钮
    const deleteBtn = document.createElement('div');
    deleteBtn.className = 'image-delete-btn';
    deleteBtn.innerHTML = '×';
    deleteBtn.title = '删除图片';
    deleteBtn.onclick = function() { deleteImage(imageData.id); };
    
    // 创建图片元素
    const img = document.createElement('img');
    img.border = '0';
    img.setAttribute('usemap', `#Map${imageData.id}`);
    
    // 使用正确的图片路径
    if (file) {
        // 如果是新上传的文件，使用服务器路径
        img.src = imageData.src;
    } else {
        img.src = imageData.src;
    }
    
    // 创建map元素
    const map = document.createElement('map');
    map.name = `Map${imageData.id}`;
    map.id = `Map${imageData.id}`;
    
    // 添加热点区域
    imageData.hotspots.forEach(hotspot => {
        const area = document.createElement('area');
        area.shape = 'rect';
        area.coords = hotspot.coords;
        area.href = hotspot.href;
        map.appendChild(area);
    });
    
    // 创建热点可视化层
    const overlay = document.createElement('div');
    overlay.className = 'hotspot-overlay';
    
    imageData.hotspots.forEach(hotspot => {
        const coords = hotspot.coords.split(',');
        const left = coords[0];
        const top = coords[1];
        const width = coords[2] - coords[0];
        const height = coords[3] - coords[1];
        
        const hotspotArea = document.createElement('div');
        hotspotArea.className = 'hotspot-area';
        hotspotArea.setAttribute('data-href', hotspot.href);
        // 使用单独的样式设置，避免cssText可能的问题
        hotspotArea.style.left = `${left}px`;
        hotspotArea.style.top = `${top}px`;
        hotspotArea.style.width = `${width}px`;
        hotspotArea.style.height = `${height}px`;
        overlay.appendChild(hotspotArea);
    });
    
    // 组装容器
    imageContainer.appendChild(deleteBtn);
    imageContainer.appendChild(img);
    imageContainer.appendChild(map);
    imageContainer.appendChild(overlay);
    
    // 添加到页面（新图片显示在最前面）
    const firstImageContainer = container.querySelector('.image-container');
    if (firstImageContainer) {
        container.insertBefore(imageContainer, firstImageContainer);
    } else {
        container.appendChild(imageContainer);
    }
    initEventListeners(); // 重新初始化事件监听器
}

// 切换Dreamweaver编辑模式
function toggleEditMode() {
    const body = document.body;
    const button = document.querySelector('button[onclick="toggleEditMode()"]');
    
    if (body.classList.contains('dreamweaver-edit')) {
        body.classList.remove('dreamweaver-edit');
        button.textContent = 'Dreamweaver编辑模式';
        button.style.background = '#28a745';
        console.log('退出Dreamweaver编辑模式，功能已启用');
    } else {
        body.classList.add('dreamweaver-edit');
        button.textContent = '正常模式';
        button.style.background = '#007bff';
        console.log('进入Dreamweaver编辑模式，热点可视化已隐藏');
    }
}

// 热点编辑功能
function showHotspotEditor() {
    const hotspotList = document.getElementById('hotspotList');
    hotspotList.innerHTML = '';
    
    // 生成热点列表
    Object.keys(hotspotInfo).forEach(href => {
        const info = hotspotInfo[href];
        const hotspotDiv = document.createElement('div');
        hotspotDiv.style.cssText = 'border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px;';
        hotspotDiv.innerHTML = `
            <h4>热点 ${href}</h4>
            <div class="form-group">
                <label>备注信息：</label>
                <textarea id="hotspot-${href}" rows="4">${info}</textarea>
            </div>
            <div class="btn-group">
                <button class="btn btn-primary" onClick="updateHotspotInfo('${href}')">更新</button>
                <button class="btn btn-danger" onClick="deleteHotspot('${href}')">删除</button>
            </div>
        `;
        hotspotList.appendChild(hotspotDiv);
    });
    
    document.getElementById('hotspotEditorModal').style.display = 'block';
}

function closeHotspotEditor() {
    document.getElementById('hotspotEditorModal').style.display = 'none';
}

function updateHotspotInfo(href) {
    const textarea = document.getElementById(`hotspot-${href}`);
    const newInfo = textarea.value.trim();
    
    if (newInfo) {
        hotspotInfo[href] = newInfo;
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 重新初始化事件监听器，确保悬浮提示使用最新的信息
        initEventListeners();
        
        showSuccess('热点信息已更新！');
    } else {
        showWarning('备注信息不能为空！');
    }
}

function deleteHotspot(href) {
    showConfirm(`确定要删除热点 ${href} 吗？`, () => {
        console.log('从编辑器删除热点:', href);
        
        delete hotspotInfo[href];
        
        // 从imageData中删除热点
        imageData.images.forEach(image => {
            const hotspotIndex = image.hotspots.findIndex(h => h.href === href);
            if (hotspotIndex !== -1) {
                image.hotspots.splice(hotspotIndex, 1);
                console.log('从imageData中删除热点:', href, '从图片', image.id);
            }
        });
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 从页面中移除对应的热点区域
        const hotspotArea = document.querySelector(`[data-href="${href}"]`);
        if (hotspotArea) {
            hotspotArea.remove();
            console.log('从页面中删除热点区域:', href);
        }
        
        // 从map中移除对应的area
        const area = document.querySelector(`area[href="${href}"]`);
        if (area) {
            area.remove();
            console.log('从map中删除area:', href);
        }
        
        // 重新同步数据到页面，确保数据一致性
        if (dataManager) {
            dataManager.syncDataToPage();
            // 重新初始化事件监听器
            if (typeof initEventListeners === 'function') {
                initEventListeners();
            }
        }
        
        showSuccess('热点已删除！');
        showHotspotEditor(); // 刷新编辑器
    });
}

function toggleDrawingMode() {
    if (isDrawingMode) {
        stopDrawingMode();
    } else {
        startDrawingMode();
    }
}

function startDrawingMode() {
    isDrawingMode = true;
    isSelectionMode = false; // 关闭选择模式
    document.body.classList.add('drawing-mode');
    
    // 如果是连续绘画模式，添加特殊样式类
    if (isContinuousDrawMode) {
        document.body.classList.add('continuous-draw-mode');
    }
    
    // 更新按钮文本和样式
    const drawingButton = document.getElementById('drawingButton');
    if (drawingButton) {
        drawingButton.textContent = '❌ 退出绘制模式';
        drawingButton.style.background = '#dc3545';
    }
    
    // 为所有热点添加编辑功能
    addDeleteButtonsToHotspots();
    
    // 显示简短提示
    console.log('绘制模式已启动 - 拖动至少5×5像素创建热点');
    if (isContinuousDrawMode) {
        showInfo('🎨 Ctrl连续绘制模式已启动！\n\n📝 拖动5×5像素创建热点\n🔄 可连续绘制多个热点\n⌨️ 松开Ctrl键退出绘制模式', 3000);
    } else {
        showInfo('绘制模式已启动！\n\n📝 拖动5×5像素创建热点\n画完热点后自动返回选择模式', 3000);
    }
}

function stopDrawingMode() {
    isDrawingMode = false;
    isSelectionMode = true; // 返回选择模式
    isContinuousDrawMode = false; // 确保退出连续绘画模式
    document.body.classList.remove('drawing-mode');
    document.body.classList.remove('continuous-draw-mode'); // 移除连续绘画模式样式
    currentDrawingImage = null;
    drawingStartPoint = null;
    
    // 重置按钮文本和样式
    const drawingButton = document.getElementById('drawingButton');
    if (drawingButton) {
        drawingButton.textContent = '🎨 编辑模式';
        drawingButton.style.background = '#ff6b35';
    }
    
    // 移除临时绘制框
    const tempBox = document.getElementById('temp-drawing-box');
    if (tempBox) {
        tempBox.remove();
    }
    
    // 移除所有编辑功能
    removeDeleteButtonsFromHotspots();
    
    // 自动保存数据
    if (dataManager && dataManager.hasUnsavedChanges) {
        console.log('退出编辑模式，自动保存数据...');
        dataManager.saveData();
        
        // 如果服务器在线，也保存到服务器
        if (serverOnline) {
            saveToProjectFile().then(success => {
                if (success) {
                    console.log('✅ 退出编辑模式，数据已自动保存到本地和服务器');
                    // 不显示提示框，因为用户只是退出编辑模式，不需要被打断
                } else {
                    console.log('⚠️ 退出编辑模式，数据已保存到本地，但服务器保存失败');
                    showWarning('数据已保存到本地，但服务器保存失败。');
                }
            });
        } else {
            console.log('⚠️ 退出编辑模式，数据已保存到本地（服务器离线）');
            // 离线模式下也不显示提示，保持流畅体验
        }
    } else {
        console.log('退出编辑模式，没有未保存的更改');
    }
}

// 显示工具提示
function showTooltip(event, text) {
    const tooltip = document.getElementById('tooltip');
    if (!tooltip) {
        console.error('工具提示元素不存在');
        return;
    }
    
    tooltip.textContent = text;
    tooltip.style.display = 'block';
    
    // 获取鼠标位置
    const mouseX = event.clientX || event.pageX;
    const mouseY = event.clientY || event.pageY;
    
    // 设置工具提示位置（鼠标上方）
    tooltip.style.left = (mouseX - tooltip.offsetWidth / 2) + 'px';
    tooltip.style.top = (mouseY - tooltip.offsetHeight - 15) + 'px';
    
    // 确保工具提示不会超出视窗边界
    const rect = tooltip.getBoundingClientRect();
    if (rect.left < 10) {
        tooltip.style.left = '10px';
    }
    if (rect.right > window.innerWidth - 10) {
        tooltip.style.left = (window.innerWidth - tooltip.offsetWidth - 10) + 'px';
    }
    if (rect.top < 10) {
        tooltip.style.top = (mouseY + 15) + 'px';
    }
}

// 隐藏工具提示
function hideTooltip() {
    const tooltip = document.getElementById('tooltip');
    if (tooltip) {
        tooltip.style.display = 'none';
    }
}

// 显示弹窗（使用多窗口系统）
function showModal(href) {
    const info = hotspotInfo[href] || '';
    const windowId = `hotspot_${href}`;
    
    // 获取热点自定义名称，如果没有则使用默认格式
    const customName = hotspotNames[href];
    const title = customName ? customName : `热点编辑器 - ${href}`;
    
    // 创建窗口内容
    const content = createModalContent(href, info);
    
    // 创建或激活窗口
    const createdWindowId = windowManager.createWindow(windowId, title, content, {
        width: 1000,
        height: 700
    });
    
    // 设置当前热点
    currentHotspot = href;
    
    // 等待窗口创建完成后初始化编辑器
    setTimeout(() => {
        initializeModalEditor(createdWindowId, href);
    }, 100);
    
    console.log('弹窗已显示:', href);
}

// 创建模态框内容（标签页模式）
function createModalContent(href, info) {
    // 清理href中的#符号，用于HTML ID
    const cleanHref = href.replace('#', '');
    
    return `
        <div class="modal-body">
            <div class="editor-container">
                <!-- 标签页头部 -->
                <div class="tab-headers">
                    <button class="tab-header active" onclick="switchTab('${href}', 'editor')">
                        📝 编辑器
                    </button>
                    <button class="tab-header" onclick="switchTab('${href}', 'preview')">
                        👁️ 预览
                    </button>
                </div>
                
                <!-- 标签页内容 -->
                <div class="tab-content">
                    <!-- 编辑器标签页 -->
                    <div id="tab-editor-${cleanHref}" class="tab-pane active">
                        <textarea id="markdown-editor-${cleanHref}" class="markdown-editor" placeholder="在此输入Markdown内容...

## 示例内容
你可以在这里写入Markdown格式的文本，支持：

### 代码高亮
\`\`\`javascript
function hello() {
    console.log('Hello World!');
}
\`\`\`

### 链接和列表
- [示例链接](https://example.com)
- **粗体文字**
- *斜体文字*

### 图片
![示例图片](IMG/example.png)

> 提示: 选中文字可以添加链接和ID标识，点击锚点链接可以跳转到对应位置并闪烁提醒"></textarea>
                    </div>
                    
                    <!-- 预览标签页 -->
                    <div id="tab-preview-${cleanHref}" class="tab-pane">
                        <div id="preview-content-${cleanHref}" class="preview-content"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <div>
                <button class="secondary" onclick="showLinkManager('${href}')">链接管理</button>
                <button class="secondary" onclick="insertTemplate('${href}')">插入模板</button>
                <button class="secondary" onclick="uploadImage('${href}')">上传图片</button>
                <button class="secondary" onclick="copyToClipboard('${href}')">复制内容</button>
            </div>
            <div>
                <button class="secondary" onclick="windowManager.closeWindow('hotspot_${href}')">取消</button>
                <button onclick="saveHotspotContentFromWindow('${href}')">保存</button>
            </div>
        </div>
    `;
}

// 初始化模态框编辑器
function initializeModalEditor(windowId, href) {
    console.log(`🔧 开始初始化编辑器 - windowId: ${windowId}, href: ${href}`);
    
    // 清理href中的#符号，确保选择器有效
    const cleanHref = href.replace('#', '');
    
    // 在窗口容器内查找编辑器元素
    const windowContainer = document.querySelector(`[data-window-id="${windowId}"]`);
    
    if (!windowContainer) {
        console.error(`❌ 找不到窗口容器: ${windowId}`);
        return;
    } else {
        console.log(`✅ 找到窗口容器:`, windowContainer);
    }
    
    const editor = windowContainer.querySelector(`#markdown-editor-${cleanHref}`);
    const preview = windowContainer.querySelector(`#preview-content-${cleanHref}`);
    
    console.log(`🔍 查找编辑器元素:`, {
        originalHref: href,
        cleanHref: cleanHref,
        editorId: `markdown-editor-${cleanHref}`,
        previewId: `preview-content-${cleanHref}`,
        editor: editor,
        preview: preview,
        editorType: editor ? editor.tagName : 'null',
        editorReadonly: editor ? editor.readOnly : 'N/A'
    });
    
    if (editor && preview) {
        // 确保编辑器可编辑
        editor.readOnly = false;
        editor.disabled = false;
        
        // 设置编辑器的初始内容为热点信息
        const hotspotContent = hotspotInfo[href] || '';
        editor.value = hotspotContent;
        
        // 设置编辑器实时更新
        editor.oninput = () => {
            console.log(`📝 编辑器内容变化: ${href}`);
            updatePreviewForWindow(href);
        };
        
        // 初始更新预览
        updatePreviewForWindow(href);
        
        // 添加文本选择功能
        addTextSelectionHandlers(preview);
        
        // 聚焦到编辑器
        setTimeout(() => {
            editor.focus();
            console.log(`🎯 编辑器已聚焦: ${href}`);
        }, 200);
        
        console.log(`✅ 编辑器已初始化: ${href}`, {
            editor: editor,
            readonly: editor.readOnly,
            disabled: editor.disabled,
            value: editor.value.substring(0, 50) + '...',
            valueLength: editor.value.length
        });
    } else {
        console.error(`❌ 编辑器初始化失败 - editor: ${!!editor}, preview: ${!!preview}`);
        console.log(`🔍 查找ID: markdown-editor-${cleanHref}, preview-content-${cleanHref}`);
        console.log(`🔍 窗口容器内容:`, windowContainer.innerHTML.substring(0, 500) + '...');
    }
}

// 标签页切换功能
function switchTab(href, tabName) {
    // 清理href中的#符号
    const cleanHref = href.replace('#', '');
    
    // 找到对应的窗口容器
    const windowId = `hotspot_${href}`;
    const windowContainer = document.querySelector(`[data-window-id="${windowId}"]`);
    
    if (!windowContainer) {
        console.error(`找不到窗口容器: ${windowId}`);
        return;
    }
    
    // 移除所有标签页的激活状态
    const headers = windowContainer.querySelectorAll('.tab-header');
    const panes = windowContainer.querySelectorAll('.tab-pane');
    
    headers.forEach(header => header.classList.remove('active'));
    panes.forEach(pane => pane.classList.remove('active'));
    
    // 激活指定的标签页
    const activeHeader = windowContainer.querySelector(`.tab-header:nth-child(${tabName === 'editor' ? '1' : '2'})`);
    const activePane = windowContainer.querySelector(`#tab-${tabName}-${cleanHref}`);
    
    if (activeHeader) {
        activeHeader.classList.add('active');
        console.log(`激活标签头: ${tabName}`);
    } else {
        console.error(`找不到标签头: ${tabName}`);
    }
    
    if (activePane) {
        activePane.classList.add('active');
        console.log(`激活标签页: ${tabName}`);
    } else {
        console.error(`找不到标签页: tab-${tabName}-${cleanHref}`);
    }
    
    // 如果切换到预览标签页，更新预览内容
    if (tabName === 'preview') {
        updatePreviewForWindow(href);
    }
    
    console.log(`切换到${tabName === 'editor' ? '编辑器' : '预览'}标签页: ${href}`);
}

// 为特定窗口更新预览
function updatePreviewForWindow(href) {
    // 清理href中的#符号
    const cleanHref = href.replace('#', '');
    
    // 在窗口容器内查找元素
    const windowId = `hotspot_${href}`;
    const windowContainer = document.querySelector(`[data-window-id="${windowId}"]`);
    
    if (!windowContainer) {
        console.error(`找不到窗口容器: ${windowId}`);
        return;
    }
    
    const editor = windowContainer.querySelector(`#markdown-editor-${cleanHref}`);
    const preview = windowContainer.querySelector(`#preview-content-${cleanHref}`);
    
    if (editor && preview) {
        const markdown = editor.value;
        
        // 使用marked.js解析Markdown
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang && Prism.languages[lang]) {
                    return Prism.highlight(code, Prism.languages[lang], lang);
                } else {
                    return code;
                }
            },
            breaks: true,
            gfm: true,
            headerIds: false,
            mangle: false
        });
        
        let html = marked.parse(markdown);
        
        // 处理Markdown锚点语法 {#id}
        html = html.replace(/\{#([^}]+)\}/g, function(match, id) {
            return '';
        });
        
        // 为标题添加锚点ID（处理 {#id} 语法）
        html = html.replace(/<(h[1-6])([^>]*)>([^<]*)\{#([^}]+)\}<\/(h[1-6])>/g, 
            '<$1$2 id="$4">$3</$5>');
        
        // 为代码块添加行号
        html = html.replace(/<pre><code class="language-(\w+)">/g, '<pre class="line-numbers"><code class="language-$1">');
        html = html.replace(/<pre><code>/g, '<pre class="line-numbers"><code>');
        
        preview.innerHTML = html;
        
        // 重新应用语法高亮
        Prism.highlightAllUnder(preview);
        
        // 为代码块添加折叠和复制按钮
        setTimeout(() => {
            const codeBlocks = preview.querySelectorAll('pre[class*="language-"], pre.line-numbers');
            console.log(`找到 ${codeBlocks.length} 个代码块`);
            
            codeBlocks.forEach((block, index) => {
                // 检查是否已经添加了按钮容器
                if (!block.querySelector('.code-btn-container')) {
                    // 创建按钮容器
                    const btnContainer = document.createElement('div');
                    btnContainer.className = 'code-btn-container';
                    
                    // 创建复制按钮
                    const copyBtn = document.createElement('button');
                    copyBtn.className = 'code-copy-btn';
                    copyBtn.textContent = '复制';
                    copyBtn.title = '复制代码到剪贴板';
                    copyBtn.onclick = function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // 获取代码内容
                        const codeElement = block.querySelector('code');
                        let codeText = '';
                        
                        if (codeElement) {
                            // 获取纯文本内容，去掉语法高亮的HTML标签
                            codeText = codeElement.textContent || codeElement.innerText || '';
                        }
                        
                        // 复制到剪贴板
                        if (navigator.clipboard && window.isSecureContext) {
                            navigator.clipboard.writeText(codeText).then(() => {
                                // 显示成功状态
                                const originalText = this.textContent;
                                this.textContent = '已复制';
                                this.classList.add('copied');
                                
                                setTimeout(() => {
                                    this.textContent = originalText;
                                    this.classList.remove('copied');
                                }, 2000);
                                
                                console.log(`代码块 ${index + 1} 已复制到剪贴板`);
                            }).catch(err => {
                                console.error('复制失败:', err);
                                this.textContent = '复制失败';
                                setTimeout(() => {
                                    this.textContent = '复制';
                                }, 2000);
                            });
                        } else {
                            // 备用方案：使用旧的复制方法
                            try {
                                const textArea = document.createElement('textarea');
                                textArea.value = codeText;
                                textArea.style.position = 'fixed';
                                textArea.style.left = '-999999px';
                                textArea.style.top = '-999999px';
                                document.body.appendChild(textArea);
                                textArea.focus();
                                textArea.select();
                                document.execCommand('copy');
                                textArea.remove();
                                
                                // 显示成功状态
                                const originalText = this.textContent;
                                this.textContent = '已复制';
                                this.classList.add('copied');
                                
                                setTimeout(() => {
                                    this.textContent = originalText;
                                    this.classList.remove('copied');
                                }, 2000);
                                
                                console.log(`代码块 ${index + 1} 已复制到剪贴板（备用方案）`);
                            } catch (err) {
                                console.error('复制失败:', err);
                                this.textContent = '复制失败';
                                setTimeout(() => {
                                    this.textContent = '复制';
                                }, 2000);
                            }
                        }
                    };
                    
                    // 创建折叠按钮
                    const foldBtn = document.createElement('button');
                    foldBtn.className = 'code-fold-btn';
                    foldBtn.textContent = '折叠';
                    foldBtn.title = '点击折叠/展开代码块';
                    foldBtn.onclick = function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        block.classList.toggle('code-folded');
                        this.textContent = block.classList.contains('code-folded') ? '展开' : '折叠';
                        
                        console.log(`代码块 ${index + 1} ${block.classList.contains('code-folded') ? '已折叠' : '已展开'}`);
                    };
                    
                    // 添加按钮到容器
                    btnContainer.appendChild(copyBtn);
                    btnContainer.appendChild(foldBtn);
                    
                    // 确保代码块有相对定位
                    block.style.position = 'relative';
                    
                    // 添加按钮容器到代码块
                    block.appendChild(btnContainer);
                    
                    console.log(`为代码块 ${index + 1} 添加了复制和折叠按钮`);
                }
            });
        }, 100); // 延迟一下，确保Prism高亮完成
        
        // 为预览中的文本添加选择功能
        addTextSelectionHandlers(preview);
        
        // 处理图片大小限制
        const images = preview.querySelectorAll('img');
        images.forEach(img => {
            img.onload = function() {
                checkImageSize(this);
            };
            img.onerror = function() {
                this.style.border = '2px solid #f92672';
                this.style.background = '#3c3c3c';
                this.alt = '图片加载失败: ' + this.src;
            };
        });
        
        // 处理链接
        const links = preview.querySelectorAll('a');
        links.forEach(link => {
            if (link.href.startsWith('http')) {
                link.target = '_blank';
                link.rel = 'noopener noreferrer';
            }
        });
    }

// 从特定窗口保存热点内容
function saveHotspotContentFromWindow(href) {
    const editor = document.getElementById(`markdown-editor-${href}`);
    if (editor) {
        const content = editor.value;
        const oldContent = hotspotInfo[href] || '';
        
        // 更新本地数据
        hotspotInfo[href] = content;
        
        // 保存到服务器
        fetch('/save_hotspot_info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                href: href,
                info: content
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showSuccess('热点信息已保存');
                console.log('保存成功:', href, content);
                
                // 记录操作日志
                if (window.operationLogs) {
                    window.operationLogs.push({
                        timestamp: new Date().toISOString(),
                        operation: 'update_hotspot_content',
                        href: href,
                        oldContent: oldContent,
                        newContent: content,
                        details: `更新热点 ${href} 的Markdown内容`
                    });
                }
            } else {
                showError('保存失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('保存失败:', error);
            showError('保存失败: 网络错误');
        });
    }
}

// 兼容旧版本的updatePreview函数
function updatePreview() {
    if (currentHotspot) {
        updatePreviewForWindow(currentHotspot);
    }
}

// 处理锚点点击（支持多窗口）
function handleAnchorClick(href, clickedElement) {
    const anchorId = href.substring(1); // 移除 # 号
    
    // 1. 首先查找当前页面的目标元素
    let targetElement = document.getElementById(anchorId) || 
                       document.querySelector(`[data-id="${anchorId}"]`) ||
                       document.querySelector(`[data-link-id="${anchorId}"]`);
    
    if (targetElement) {
        // 如果在当前页面找到目标，直接滚动并闪烁
        scrollToElementAndBlink(targetElement);
        showSuccess(`已跳转到锚点: ${anchorId}`);
        return;
    }
    
    // 2. 在已打开的窗口中查找锚点
    for (const [windowId, windowInfo] of windowManager.windows) {
        if (!windowInfo.isMinimized && windowId.startsWith('hotspot_')) {
            const preview = document.getElementById(`preview-content-${windowId.substring(8)}`);
            if (preview) {
                const target = preview.querySelector(`#${anchorId}`) || 
                              preview.querySelector(`[data-id="${anchorId}"]`) ||
                              preview.querySelector(`[data-link-id="${anchorId}"]`);
                
                if (target) {
                    // 激活包含目标的窗口
                    windowManager.activateWindow(windowId);
                    // 滚动到目标并闪烁
                    setTimeout(() => {
                        scrollToElementAndBlink(target);
                        showSuccess(`已在窗口 ${windowInfo.title} 中找到锚点: ${anchorId}`);
                    }, 200);
                    return;
                }
            }
        }
    }
    
    // 3. 检查是否是热点链接格式 (如 #hotspot-xxx)
    if (anchorId.startsWith('hotspot-')) {
        const hotspotId = anchorId.substring(8); // 移除 "hotspot-" 前缀
        if (hotspotInfo[hotspotId]) {
            // 打开对应热点的模态框
            showModal(hotspotId);
            showSuccess(`已打开热点: ${hotspotId}`);
            return;
        }
    }
    
    // 4. 搜索所有热点内容中是否包含该锚点
    const foundHotspot = findAnchorInHotspots(anchorId);
    if (foundHotspot) {
        // 打开包含该锚点的热点模态框
        showModal(foundHotspot.hotspot);
        
        // 等待模态框加载完成后查找目标元素
        setTimeout(() => {
            const preview = document.getElementById(`preview-content-${foundHotspot.hotspot}`);
            if (preview) {
                const target = preview.querySelector(`#${anchorId}`) || 
                              preview.querySelector(`[data-id="${anchorId}"]`) ||
                              preview.querySelector(`[data-link-id="${anchorId}"]`);
                
                if (target) {
                    scrollToElementAndBlink(target);
                    showSuccess(`已在热点 ${foundHotspot.hotspot} 中找到锚点: ${anchorId}`);
                } else {
                    showWarning(`已打开热点 ${foundHotspot.hotspot}，但未找到锚点: ${anchorId}`);
                }
            }
        }, 500);
        return;
    }
    
    // 5. 如果都没找到，显示提示
    showError(`未找到锚点目标: ${anchorId}`);
}

// 在所有热点内容中搜索锚点
function findAnchorInHotspots(anchorId) {
    for (const [hotspotId, content] of Object.entries(hotspotInfo)) {
        if (content && typeof content === 'string') {
            // 检查Markdown内容中是否包含该锚点ID
            const patterns = [
                new RegExp(`id="${anchorId}"`, 'i'),           // HTML id属性
                new RegExp(`data-id="${anchorId}"`, 'i'),      // data-id属性  
                new RegExp(`\\{#${anchorId}\\}`, 'i'),         // Markdown锚点语法
                new RegExp(`<.*?id=['"]${anchorId}['"].*?>`, 'i'), // HTML标签
                new RegExp(`\\[.*?\\]\\(#${anchorId}\\)`, 'i') // Markdown链接
            ];
            
            if (patterns.some(pattern => pattern.test(content))) {
                return { hotspot: hotspotId, content: content };
            }
        }
    }
    return null;
}

// 滚动到元素并闪烁提醒
function scrollToElementAndBlink(element) {
    if (!element) return;
    
    // 滚动到目标元素
    element.scrollIntoView({ 
        behavior: 'smooth', 
        block: 'center',
        inline: 'nearest'
    });
    
    // 添加CSS动画类
    element.classList.add('anchor-target');
    
    // 3秒后移除动画类
    setTimeout(() => {
        element.classList.remove('anchor-target');
    }, 1800);
    
    // 临时高亮显示锚点信息
    if (element.id || element.getAttribute('data-id')) {
        const anchorId = element.id || element.getAttribute('data-id');
        showSuccess(`🎯 已跳转到锚点: ${anchorId}`, 2000);
    }
}

// 检查图片大小
function checkImageSize(img) {
    // 这里可以添加图片大小检查逻辑
    // 目前只是一个占位函数
    const maxSize = 50 * 1024 * 1024; // 50MB
    console.log('图片加载完成:', img.src);
}

// 添加文本选择处理
function addTextSelectionHandlers(container) {
    container.addEventListener('mouseup', handleTextSelection);
    container.addEventListener('dblclick', handleDoubleClick);
    
    // 屏蔽右键菜单在文本选择时
    container.addEventListener('contextmenu', function(event) {
        const selection = window.getSelection();
        if (selection.toString().trim().length > 0) {
            event.preventDefault();
            event.stopPropagation();
            // 显示自定义菜单而不是系统右键菜单
            showTextSelectionMenu(event, selection);
            return false;
        }
    });
    
    // 为锚点链接添加点击处理
    container.addEventListener('click', function(event) {
        const target = event.target;
        if (target.tagName === 'A' && target.href) {
            const href = target.getAttribute('href');
            // 检查是否是锚点链接
            if (href && href.startsWith('#')) {
                event.preventDefault();
                event.stopPropagation();
                handleAnchorClick(href, target);
                return false;
            }
        }
    });
}

// 处理文本选择
function handleTextSelection(event) {
    const selection = window.getSelection();
    if (selection.toString().trim().length > 0) {
        showTextSelectionMenu(event, selection);
    } else {
        hideTextSelectionMenu();
    }
}

// 处理双击
function handleDoubleClick(event) {
    const selection = window.getSelection();
    if (selection.toString().trim().length > 0) {
        showTextSelectionMenu(event, selection);
    }
}

// 显示文本选择菜单
function showTextSelectionMenu(event, selection) {
    const menu = document.getElementById('text-selection-menu');
    if (menu) {
        // 防止浏览器默认右键菜单
        event.preventDefault();
        event.stopPropagation();
        
        menu.style.display = 'block';
        menu.style.left = event.pageX + 'px';
        menu.style.top = event.pageY + 'px';
        
        // 保存当前选择
        window.currentSelection = selection;
        window.currentSelectionRange = selection.getRangeAt(0);
        
        // 确保菜单不会超出视窗边界
        const rect = menu.getBoundingClientRect();
        if (rect.right > window.innerWidth - 10) {
            menu.style.left = (window.innerWidth - rect.width - 10) + 'px';
        }
        if (rect.bottom > window.innerHeight - 10) {
            menu.style.top = (event.pageY - rect.height - 10) + 'px';
        }
    }
}

// 隐藏文本选择菜单
function hideTextSelectionMenu() {
    const menu = document.getElementById('text-selection-menu');
    if (menu) {
        menu.style.display = 'none';
    }
}

// 为选中文本添加链接
function addLinkToSelection() {
    if (!window.currentSelection || !window.currentSelectionRange) return;
    
    const text = window.currentSelection.toString();
    
    // 创建更智能的链接输入对话框
    const linkDialog = document.createElement('div');
    linkDialog.className = 'link-dialog';
    linkDialog.innerHTML = `
        <div class="link-dialog-content">
            <h4>添加链接</h4>
            <p>选中文本: <strong>"${text}"</strong></p>
            <div class="form-group">
                <label>链接类型:</label>
                <select id="linkType">
                    <option value="url">网址链接</option>
                    <option value="hotspot">热点链接</option>
                    <option value="anchor">锚点链接</option>
                </select>
            </div>
            <div class="form-group">
                <label>链接地址:</label>
                <div class="link-input-container">
                    <input type="text" id="linkUrl" placeholder="请输入链接地址" value="https://">
                    <button id="showLinkSelector" type="button" style="display: none;">选择</button>
                </div>
            </div>
            <!-- 链接选择器 -->
            <div id="linkSelector" class="link-selector" style="display: none;">
                <div class="selector-header">
                    <input type="text" id="linkSearch" placeholder="输入关键词搜索..." />
                    <span class="search-count" id="searchCount"></span>
                </div>
                <div class="selector-content" id="selectorContent">
                    <!-- 动态生成的选项列表 -->
                </div>
            </div>
            <div class="btn-group">
                <button onclick="cancelLinkDialog()">取消</button>
                <button onclick="confirmLinkDialog()">确定</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(linkDialog);
    
    // 添加样式
    linkDialog.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #2b2b2b;
        border: 1px solid #555;
        border-radius: 8px;
        padding: 20px;
        z-index: 10003;
        color: #f8f8f2;
        min-width: 500px;
        max-width: 700px;
        max-height: 80vh;
        overflow-y: auto;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    `;
    
    const linkTypeSelect = document.getElementById('linkType');
    const linkUrlInput = document.getElementById('linkUrl');
    const showSelectorBtn = document.getElementById('showLinkSelector');
    const linkSelector = document.getElementById('linkSelector');
    const linkSearch = document.getElementById('linkSearch');
    
    linkTypeSelect.onchange = function() {
        switch(this.value) {
            case 'url':
                linkUrlInput.placeholder = '请输入网址 (如: https://example.com)';
                linkUrlInput.value = 'https://';
                showSelectorBtn.style.display = 'none';
                linkSelector.style.display = 'none';
                break;
            case 'hotspot':
                linkUrlInput.placeholder = '请选择热点或输入热点ID';
                linkUrlInput.value = '#hotspot-';
                showSelectorBtn.style.display = 'inline-block';
                linkSelector.style.display = 'block';
                populateHotspotSelector();
                break;
            case 'anchor':
                linkUrlInput.placeholder = '请选择锚点或输入锚点ID';
                linkUrlInput.value = '#';
                showSelectorBtn.style.display = 'inline-block';
                linkSelector.style.display = 'block';
                populateAnchorSelector();
                break;
        }
    };
    
    // 搜索功能
    linkSearch.oninput = function() {
        const searchTerm = this.value.toLowerCase();
        filterSelectorOptions(searchTerm);
    };
    
    // 选择器按钮点击
    showSelectorBtn.onclick = function() {
        linkSelector.style.display = linkSelector.style.display === 'none' ? 'block' : 'none';
    };
    
    // 自动聚焦到输入框
    setTimeout(() => linkUrlInput.focus(), 100);
    
    // 保存当前选择
    window.currentLinkText = text;
    
    hideTextSelectionMenu();
}

// 确认添加链接
function confirmLinkDialog() {
    const linkUrl = document.getElementById('linkUrl').value;
    const linkType = document.getElementById('linkType').value;
    const text = window.currentLinkText;
    
    // 验证链接地址
    if (!linkUrl || linkUrl.trim() === '') {
        showError('请输入或选择链接地址');
        return;
    }
    
    // 根据类型验证格式
    if (linkType === 'url' && (linkUrl === 'https://' || !linkUrl.startsWith('http'))) {
        showError('请输入有效的网址');
        return;
    }
    
    if (linkType === 'hotspot' && (linkUrl === '#hotspot-' || !linkUrl.startsWith('#hotspot-'))) {
        showError('请选择有效的热点');
        return;
    }
    
    if (linkType === 'anchor' && (linkUrl === '#' || !linkUrl.startsWith('#'))) {
        showError('请选择有效的锚点');
        return;
    }
    
    if (text && window.currentSelectionRange) {
        const linkId = generateUniqueId();
        const linkElement = document.createElement('a');
        linkElement.href = linkUrl;
        linkElement.textContent = text;
        linkElement.setAttribute('data-link-id', linkId);
        linkElement.className = 'text-with-id';
        
        // 设置标题提示
        let titleText = `链接到: ${linkUrl}`;
        if (linkType === 'hotspot') {
            const hotspotId = linkUrl.substring(9); // 移除 "#hotspot-"
            titleText = `跳转到热点: ${hotspotId}`;
        } else if (linkType === 'anchor') {
            const anchorId = linkUrl.substring(1); // 移除 "#"
            titleText = `跳转到锚点: ${anchorId}`;
        }
        linkElement.title = titleText;
        
        // 根据链接类型设置样式
        if (linkType === 'hotspot') {
            linkElement.style.borderBottomColor = '#a6e22e';
        } else if (linkType === 'anchor') {
            linkElement.style.borderBottomColor = '#e6db74';
        }
        
        // 替换选中的文本
        window.currentSelectionRange.deleteContents();
        window.currentSelectionRange.insertNode(linkElement);
        
        // 保存链接信息
        saveLink(linkId, text, linkUrl, currentHotspot, linkType);
        
        const linkTypeText = linkType === 'url' ? '网址' : 
                           linkType === 'hotspot' ? '热点' : '锚点';
        showSuccess(`已添加${linkTypeText}链接: ${linkUrl}`);
    }
    
    cancelLinkDialog();
}

// 填充热点选择器
function populateHotspotSelector() {
    const selectorContent = document.getElementById('selectorContent');
    const searchCount = document.getElementById('searchCount');
    
    if (!selectorContent) return;
    
    selectorContent.innerHTML = '';
    
    if (!hotspotInfo || Object.keys(hotspotInfo).length === 0) {
        selectorContent.innerHTML = '<div class="no-options">暂无可用热点</div>';
        searchCount.textContent = '0 个热点';
        return;
    }
    
    const hotspots = Object.keys(hotspotInfo);
    searchCount.textContent = `${hotspots.length} 个热点`;
    
    hotspots.forEach(hotspotId => {
        const content = hotspotInfo[hotspotId] || '';
        const preview = content.substring(0, 100).replace(/\n/g, ' ') + (content.length > 100 ? '...' : '');
        
        const option = document.createElement('div');
        option.className = 'selector-option';
        option.setAttribute('data-type', 'hotspot');
        option.setAttribute('data-id', hotspotId);
        option.setAttribute('data-search', `${hotspotId} ${content}`.toLowerCase());
        
        option.innerHTML = `
            <div class="option-title">🎯 ${hotspotId}</div>
            <div class="option-preview">${preview}</div>
            <div class="option-link">#hotspot-${hotspotId}</div>
        `;
        
        option.onclick = function() {
            document.getElementById('linkUrl').value = `#hotspot-${hotspotId}`;
            highlightSelectedOption(this);
        };
        
        selectorContent.appendChild(option);
    });
}

// 填充锚点选择器
function populateAnchorSelector() {
    const selectorContent = document.getElementById('selectorContent');
    const searchCount = document.getElementById('searchCount');
    
    if (!selectorContent) return;
    
    selectorContent.innerHTML = '';
    
    const anchors = collectAllAnchors();
    
    if (anchors.length === 0) {
        selectorContent.innerHTML = '<div class="no-options">暂无可用锚点</div>';
        searchCount.textContent = '0 个锚点';
        return;
    }
    
    searchCount.textContent = `${anchors.length} 个锚点`;
    
    anchors.forEach(anchor => {
        const option = document.createElement('div');
        option.className = 'selector-option';
        option.setAttribute('data-type', 'anchor');
        option.setAttribute('data-id', anchor.id);
        option.setAttribute('data-search', `${anchor.id} ${anchor.text} ${anchor.hotspot}`.toLowerCase());
        
        const typeIcon = anchor.source === 'current' ? '📍' : 
                        anchor.source === 'storage' ? '🏷️' : '📄';
        
        option.innerHTML = `
            <div class="option-title">${typeIcon} ${anchor.id}</div>
            <div class="option-preview">${anchor.text}</div>
            <div class="option-source">来源: ${anchor.hotspot || '当前页面'}</div>
            <div class="option-link">#${anchor.id}</div>
        `;
        
        option.onclick = function() {
            document.getElementById('linkUrl').value = `#${anchor.id}`;
            highlightSelectedOption(this);
        };
        
        selectorContent.appendChild(option);
    });
}

// 收集所有可用的锚点
function collectAllAnchors() {
    const anchors = [];
    
    // 1. 收集当前页面的锚点
    const currentPageElements = document.querySelectorAll('[id], [data-id]');
    currentPageElements.forEach(element => {
        const id = element.id || element.getAttribute('data-id');
        if (id && !id.startsWith('temp-')) {
            const text = element.textContent.substring(0, 50) + 
                        (element.textContent.length > 50 ? '...' : '');
            anchors.push({
                id: id,
                text: text,
                hotspot: '当前页面',
                source: 'current'
            });
        }
    });
    
    // 2. 收集存储的ID标识
    if (window.idStorage) {
        Object.keys(window.idStorage).forEach(id => {
            const idInfo = window.idStorage[id];
            anchors.push({
                id: id,
                text: idInfo.text,
                hotspot: idInfo.hotspot,
                source: 'storage'
            });
        });
    }
    
    // 3. 从所有热点内容中提取锚点
    if (hotspotInfo) {
        Object.keys(hotspotInfo).forEach(hotspotId => {
            const content = hotspotInfo[hotspotId];
            if (content && typeof content === 'string') {
                // 提取Markdown标题锚点 {#id}
                const titleMatches = content.match(/#{1,6}\s+([^{]+)\s*\{#([^}]+)\}/g);
                if (titleMatches) {
                    titleMatches.forEach(match => {
                        const titleMatch = match.match(/#{1,6}\s+([^{]+)\s*\{#([^}]+)\}/);
                        if (titleMatch) {
                            anchors.push({
                                id: titleMatch[2],
                                text: titleMatch[1].trim(),
                                hotspot: hotspotId,
                                source: 'markdown'
                            });
                        }
                    });
                }
                
                // 提取HTML id属性
                const htmlMatches = content.match(/id=["']([^"']+)["']/g);
                if (htmlMatches) {
                    htmlMatches.forEach(match => {
                        const idMatch = match.match(/id=["']([^"']+)["']/);
                        if (idMatch) {
                            // 尝试找到对应的文本
                            const textMatch = content.match(new RegExp(`<[^>]*id=["']${idMatch[1]}["'][^>]*>([^<]*)<`, 'i'));
                            const text = textMatch ? textMatch[1] : idMatch[1];
                            
                            anchors.push({
                                id: idMatch[1],
                                text: text,
                                hotspot: hotspotId,
                                source: 'html'
                            });
                        }
                    });
                }
            }
        });
    }
    
    // 去重（基于id）
    const uniqueAnchors = anchors.filter((anchor, index, self) => 
        index === self.findIndex(a => a.id === anchor.id)
    );
    
    return uniqueAnchors.sort((a, b) => a.id.localeCompare(b.id));
}

// 过滤选择器选项
function filterSelectorOptions(searchTerm) {
    const options = document.querySelectorAll('.selector-option');
    const searchCount = document.getElementById('searchCount');
    let visibleCount = 0;
    
    options.forEach(option => {
        const searchText = option.getAttribute('data-search') || '';
        const isVisible = searchTerm === '' || searchText.includes(searchTerm);
        
        option.style.display = isVisible ? 'block' : 'none';
        if (isVisible) visibleCount++;
    });
    
    const totalCount = options.length;
    const type = document.getElementById('linkType').value === 'hotspot' ? '热点' : '锚点';
    searchCount.textContent = searchTerm ? 
        `显示 ${visibleCount} / ${totalCount} 个${type}` : 
        `${totalCount} 个${type}`;
}

// 高亮选中的选项
function highlightSelectedOption(selectedOption) {
    // 移除其他选项的高亮
    document.querySelectorAll('.selector-option').forEach(option => {
        option.classList.remove('selected');
    });
    
    // 高亮当前选项
    selectedOption.classList.add('selected');
}

// 取消链接对话框
function cancelLinkDialog() {
    const linkDialog = document.querySelector('.link-dialog');
    if (linkDialog) {
        linkDialog.remove();
    }
    window.currentLinkText = null;
}

// 为选中文本添加ID
function addIdToSelection() {
    if (!window.currentSelection || !window.currentSelectionRange) return;
    
    const text = window.currentSelection.toString();
    let id = prompt('请输入ID (留空自动生成，用于锚点跳转):', '');
    
    if (id === null) return; // 用户取消
    
    if (!id) {
        id = generateReadableId(text);
    }
    
    // 检查ID是否已存在
    if (isIdExists(id)) {
        alert('ID已存在，请使用其他ID');
        return;
    }
    
    const spanElement = document.createElement('span');
    spanElement.textContent = text;
    spanElement.setAttribute('data-id', id);
    spanElement.setAttribute('id', id); // 同时添加HTML id属性用于锚点跳转
    spanElement.className = 'text-with-id';
    spanElement.title = `锚点ID: ${id} (可通过 #${id} 链接跳转)`;
    
    // 替换选中的文本
    window.currentSelectionRange.deleteContents();
    window.currentSelectionRange.insertNode(spanElement);
    
    // 保存ID信息
    saveTextId(id, text, currentHotspot);
    
    // 更新编辑器内容
    updateEditorFromPreview();
    
    showSuccess(`已添加锚点ID: ${id}`);
    
    hideTextSelectionMenu();
}

// 生成可读的ID
function generateReadableId(text) {
    // 提取文本的关键词作为ID
    const cleanText = text
        .replace(/[^\w\u4e00-\u9fa5\s]/g, '') // 移除特殊字符，保留中英文
        .replace(/\s+/g, '-') // 空格替换为横线
        .toLowerCase()
        .substring(0, 20); // 限制长度
    
    const timestamp = Date.now().toString().slice(-4); // 最后4位时间戳
    return cleanText ? `${cleanText}-${timestamp}` : `anchor-${timestamp}`;
}

// 移除选中文本的ID
function removeIdFromSelection() {
    if (!window.currentSelection || !window.currentSelectionRange) return;
    
    const range = window.currentSelectionRange;
    const container = range.commonAncestorContainer;
    let element = container.nodeType === Node.TEXT_NODE ? container.parentNode : container;
    
    if (element.hasAttribute('data-id')) {
        const text = element.textContent;
        const textNode = document.createTextNode(text);
        element.parentNode.replaceChild(textNode, element);
        
        // 更新编辑器内容
        updateEditorFromPreview();
    }
    
    hideTextSelectionMenu();
}

// 生成唯一ID
function generateUniqueId() {
    return 'id_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 检查ID是否存在
function isIdExists(id) {
    // 这里可以检查全局ID存储
    return document.querySelector(`[data-id="${id}"]`) !== null;
}

// 保存链接信息
function saveLink(linkId, text, url, hotspot, linkType = 'url') {
    if (!window.linkStorage) {
        window.linkStorage = {};
    }
    
    window.linkStorage[linkId] = {
        text: text,
        url: url,
        hotspot: hotspot,
        linkType: linkType,
        type: 'link',
        createdAt: new Date().toISOString()
    };
}

// 保存文本ID信息
function saveTextId(id, text, hotspot) {
    if (!window.idStorage) {
        window.idStorage = {};
    }
    
    window.idStorage[id] = {
        text: text,
        hotspot: hotspot,
        type: 'text-id'
    };
}

// 从预览更新编辑器
function updateEditorFromPreview() {
    const preview = document.getElementById('preview-content');
    const editor = document.getElementById('markdown-editor');
    
    if (preview && editor) {
        // 这里需要将HTML转换回Markdown
        // 暂时保持编辑器内容不变，实际应用中可能需要更复杂的转换
        console.log('需要更新编辑器内容');
    }
}

// 保存热点内容
function saveHotspotContent() {
    const editor = document.getElementById('markdown-editor');
    if (editor && currentHotspot) {
        const content = editor.value;
        const oldContent = hotspotInfo[currentHotspot] || '';
        
        // 更新本地数据
        hotspotInfo[currentHotspot] = content;
        
        // 保存到服务器
        fetch('/save_hotspot_info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                href: currentHotspot,
                info: content
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showSuccess('热点信息已保存');
                console.log('保存成功:', currentHotspot, content);
                
                // 记录操作日志
                if (window.operationLogs) {
                    window.operationLogs.push({
                        timestamp: new Date().toISOString(),
                        operation: 'update_hotspot_content',
                        href: currentHotspot,
                        oldContent: oldContent,
                        newContent: content,
                        details: `更新热点 ${currentHotspot} 的Markdown内容`
                    });
                }
            } else {
                showError('保存失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('保存失败:', error);
            showError('保存失败: 网络错误');
        });
        
        closeModal();
    }
}

// 显示链接管理器
function showLinkManager() {
    const manager = document.getElementById('link-manager');
    const linkList = document.getElementById('link-list');
    
    if (manager && linkList) {
        // 清空列表
        linkList.innerHTML = '';
        
        let hasItems = false;
        
        // 添加链接项
        if (window.linkStorage) {
            Object.keys(window.linkStorage).forEach(id => {
                const link = window.linkStorage[id];
                hasItems = true;
                const linkTypeText = link.linkType === 'url' ? '🌐 网址' : 
                                   link.linkType === 'hotspot' ? '🎯 热点' : 
                                   link.linkType === 'anchor' ? '⚓ 锚点' : '🔗 链接';
                
                const item = document.createElement('div');
                item.className = 'link-item';
                item.innerHTML = `
                    <div class="source">
                        ${linkTypeText} "${link.text}"
                        <span style="font-size: 12px; color: #75715e; margin-left: 8px;">
                            ${link.hotspot || '未知热点'}
                        </span>
                    </div>
                    <div class="target">链接: ${link.url}</div>
                    <div style="margin-top: 8px;">
                        <button onclick="editLink('${id}')" style="background: #75715e; color: #f8f8f2; border: none; padding: 4px 8px; border-radius: 3px; margin-right: 4px;">编辑</button>
                        <button onclick="copyLinkUrl('${id}')" style="background: #66d9ef; color: #272822; border: none; padding: 4px 8px; border-radius: 3px; margin-right: 4px;">复制</button>
                        <button onclick="deleteLink('${id}')" style="background: #f92672; color: #f8f8f2; border: none; padding: 4px 8px; border-radius: 3px;">删除</button>
                    </div>
                `;
                linkList.appendChild(item);
            });
        }
        
        // 添加ID项
        if (window.idStorage) {
            Object.keys(window.idStorage).forEach(id => {
                const textId = window.idStorage[id];
                hasItems = true;
                const item = document.createElement('div');
                item.className = 'link-item';
                item.innerHTML = `
                    <div class="source">
                        🏷️ ID标识: <code>${id}</code>
                        <span style="font-size: 12px; color: #75715e; margin-left: 8px;">
                            ${textId.hotspot || '未知热点'}
                        </span>
                    </div>
                    <div class="target">文本: "${textId.text}"</div>
                    <div style="margin-top: 8px;">
                        <button onclick="copyTextId('${id}')" style="background: #66d9ef; color: #272822; border: none; padding: 4px 8px; border-radius: 3px; margin-right: 4px;">复制ID</button>
                        <button onclick="deleteTextId('${id}')" style="background: #f92672; color: #f8f8f2; border: none; padding: 4px 8px; border-radius: 3px;">删除</button>
                    </div>
                `;
                linkList.appendChild(item);
            });
        }
        
        if (!hasItems) {
            linkList.innerHTML = '<p style="text-align: center; color: #75715e; margin: 20px 0;">暂无链接或ID标识</p>';
        }
        
        manager.style.display = 'block';
    }
}

// 复制链接URL
function copyLinkUrl(linkId) {
    if (window.linkStorage && window.linkStorage[linkId]) {
        const url = window.linkStorage[linkId].url;
        navigator.clipboard.writeText(url).then(() => {
            showSuccess('链接地址已复制');
        }).catch(() => {
            showError('复制失败');
        });
    }
}

// 复制文本ID
function copyTextId(id) {
    navigator.clipboard.writeText(id).then(() => {
        showSuccess('ID已复制');
    }).catch(() => {
        showError('复制失败');
    });
}

// 关闭链接管理器
function closeLinkManager() {
    const manager = document.getElementById('link-manager');
    if (manager) {
        manager.style.display = 'none';
    }
}

// 插入模板
function insertTemplate() {
    const templates = {
        'basic': {
            name: '基础模板',
            content: `# 标题

## 功能说明 {#function-desc}

这里是功能说明...

## 代码示例 {#code-example}

\`\`\`javascript
function example() {
    console.log("Hello World!");
    return true;
}
\`\`\`

## 相关链接

- [跳转到功能说明](#function-desc)
- [查看代码示例](#code-example)
- [外部链接](https://example.com)

---

> 提示: 选中文字可以添加链接和ID标识，点击锚点链接可以跳转到对应位置并闪烁提醒`
        },
        'api': {
            name: 'API文档模板',
            content: `# API 接口

## 请求地址
\`POST /api/example\`

## 请求参数

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| name   | string | 是 | 用户名 |
| age    | number | 否 | 年龄 |

## 请求示例

\`\`\`json
{
    "name": "张三",
    "age": 25
}
\`\`\`

## 响应示例

\`\`\`json
{
    "code": 200,
    "message": "success",
    "data": {
        "id": 1,
        "name": "张三"
    }
}
\`\`\``
        },
        'tutorial': {
            name: '教程模板',
            content: `# 教程：智能链接选择器使用指南

## 目录

- [功能概述](#overview)
- [热点链接](#hotspot-links)  
- [锚点链接](#anchor-links)
- [搜索功能](#search-feature)
- [实际操作](#practice)

## 功能概述 {#overview}

新的智能链接选择器提供以下功能：

1. **自动列出所有可用选项**
   - 🎯 热点链接：显示所有现有热点
   - ⚓ 锚点链接：显示所有可用锚点

2. **智能搜索**
   - 支持关键词搜索
   - 实时过滤结果
   - 显示匹配数量

3. **预览信息**
   - 显示链接目标的内容预览
   - 标明来源热点
   - 显示完整链接地址

## 热点链接使用 {#hotspot-links}

### 创建热点链接步骤：
1. 选中要添加链接的文字
2. 右键选择"添加链接"
3. 选择"热点链接"类型
4. 在选择器中浏览或搜索目标热点
5. 点击选择，确定添加

### 热点链接示例：
- [跳转到主页热点](#hotspot-main)
- [查看配置热点](#hotspot-config)

## 锚点链接使用 {#anchor-links}

### 锚点来源：
- 📍 **当前页面**：页面内的所有ID元素
- 🏷️ **ID标识**：通过"添加ID"功能创建的标识
- 📄 **Markdown锚点**：标题中的 \`{#id}\` 语法
- 🔗 **HTML锚点**：HTML元素的id属性

### 锚点链接示例：
- [返回目录](#目录)
- [跳转到功能概述](#overview)
- [查看搜索功能](#search-feature)

## 搜索功能 {#search-feature}

### 搜索范围：
- 热点ID和内容
- 锚点ID和相关文字
- 所属热点名称

### 搜索技巧：
- 输入关键词即可实时搜索
- 支持中英文搜索
- 部分匹配即可显示结果

### 搜索示例：
\`\`\`
搜索 "配置" → 找到所有包含配置的热点和锚点
搜索 "config" → 找到所有包含config的项目  
搜索 "功能" → 找到所有功能相关的内容
\`\`\`

## 实际操作 {#practice}

### 练习1：创建热点链接
1. 选中这段文字：**"点击跳转到其他热点"**
2. 添加热点链接
3. 在选择器中选择任意热点

### 练习2：创建锚点链接  
1. 选中这段文字：**"返回到教程开始"**
2. 添加锚点链接
3. 搜索 "教程" 找到对应锚点

### 练习3：使用搜索功能
1. 选择锚点链接类型
2. 在搜索框输入 "功能"
3. 观察过滤结果
4. 选择合适的锚点

## 高级功能

### 自动识别
系统会自动收集以下锚点：
- 所有HTML元素的id属性
- Markdown标题的锚点语法
- 用户添加的ID标识
- 当前页面的所有可跳转元素

### 跨热点跳转
- 可以从一个热点链接到另一个热点的特定位置
- 自动打开目标热点的模态框
- 跳转到指定锚点并闪烁提醒

[回到顶部](#教程：智能链接选择器使用指南)

---

> 💡 **提示**: 
> - 选择器会显示所有可用选项，无需记忆具体ID
> - 搜索功能让查找变得更简单
> - 预览信息帮助确认正确的目标`
        },
        'database': {
            name: '数据库模板',
            content: `# 数据库设计

## 表结构

### users 用户表

| 字段名 | 类型 | 长度 | 允许空 | 默认值 | 说明 |
|--------|------|------|--------|--------|------|
| id | int | 11 | 否 | AUTO_INCREMENT | 主键 |
| username | varchar | 50 | 否 | | 用户名 |
| email | varchar | 100 | 否 | | 邮箱 |
| created_at | timestamp | | 否 | CURRENT_TIMESTAMP | 创建时间 |

## SQL 示例

### 创建表
\`\`\`sql
CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);
\`\`\`

### 查询数据
\`\`\`sql
SELECT * FROM users WHERE username = 'admin';
\`\`\``
        }
    };
    
    // 创建模板选择对话框
    const templateNames = Object.keys(templates);
    let templateList = '请选择模板:\n\n';
    templateNames.forEach((key, index) => {
        templateList += `${index + 1}. ${templates[key].name}\n`;
    });
    
    const choice = prompt(templateList + '\n请输入模板编号 (1-' + templateNames.length + '):');
    const templateIndex = parseInt(choice) - 1;
    
    if (templateIndex >= 0 && templateIndex < templateNames.length) {
        const selectedTemplate = templates[templateNames[templateIndex]];
        const editor = document.getElementById('markdown-editor');
        if (editor) {
            editor.value = selectedTemplate.content;
            updatePreview();
            showSuccess(`已插入${selectedTemplate.name}`);
        }
    } else if (choice !== null) {
        showError('无效的模板编号');
    }
}

// 上传图片
function uploadImage() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件大小 (50MB)
            if (file.size > 50 * 1024 * 1024) {
                alert('图片文件不能超过50MB');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                const editor = document.getElementById('markdown-editor');
                if (editor) {
                    const imageMarkdown = `\n![${file.name}](${e.target.result})\n`;
                    const cursorPos = editor.selectionStart;
                    const textBefore = editor.value.substring(0, cursorPos);
                    const textAfter = editor.value.substring(cursorPos);
                    editor.value = textBefore + imageMarkdown + textAfter;
                    updatePreview();
                }
            };
            reader.readAsDataURL(file);
        }
    };
    input.click();
}

// 关闭弹窗（兼容旧版本，现在使用多窗口系统）
function closeModal() {
    // 如果有当前热点，关闭对应的窗口
    if (currentHotspot) {
        windowManager.closeWindow(`hotspot_${currentHotspot}`);
        currentHotspot = null;
        return;
    }
    
    // 向后兼容：如果还有旧的模态框存在，关闭它
    const modal = document.getElementById('modal');
    if (modal && modal.style.display !== 'none') {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
}

// 复制到剪贴板
function copyToClipboard() {
    const editor = document.getElementById('markdown-editor');
    if (editor && currentHotspot) {
        const content = editor.value;
        navigator.clipboard.writeText(content).then(function() {
            showSuccess('内容已复制到剪贴板');
        }).catch(function(err) {
            console.error('复制失败:', err);
            showError('复制失败');
        });
    }
}

// 初始化事件监听器
function initEventListeners() {
    // 为所有热点可视化区域添加事件
    const hotspotAreas = document.querySelectorAll('.hotspot-area');
    console.log('找到热点区域数量:', hotspotAreas.length);
    
    hotspotAreas.forEach((area, index) => {
        const href = area.getAttribute('data-href');
        const info = hotspotInfo[href];
        
        console.log(`热点区域 ${index + 1}:`, href, info);
        
        // 移除旧的事件监听器（如果存在）
        area.removeEventListener('mouseenter', area._mouseenterHandler);
        area.removeEventListener('mouseleave', area._mouseleaveHandler);
        area.removeEventListener('click', area._clickHandler);
        area.removeEventListener('dblclick', area._dblclickHandler);
        
        if (info) {
            // 创建事件处理函数并保存引用
            area._mouseenterHandler = function(event) {
                console.log('鼠标进入热点:', href);
                showTooltip(event, info);
            };
            
            area._mouseleaveHandler = function() {
                console.log('鼠标离开热点:', href);
                hideTooltip();
            };
            
            area._clickHandler = function(event) {
                if (isDrawingMode) {
                    // 在绘制模式下，点击不显示弹窗
                    return;
                }
                event.preventDefault();
                console.log('单击热点:', href);
                // 单击不再显示弹窗，只显示tooltip
            };
            
            area._dblclickHandler = function(event) {
                if (isDrawingMode) {
                    // 在绘制模式下，双击不显示弹窗
                    return;
                }
                event.preventDefault();
                console.log('双击热点:', href);
                hideTooltip(); // 隐藏tooltip
                showModal(href);
            };
            
            // 添加新的事件监听器
            area.addEventListener('mouseenter', area._mouseenterHandler);
            area.addEventListener('mouseleave', area._mouseleaveHandler);
            area.addEventListener('click', area._clickHandler);
            area.addEventListener('dblclick', area._dblclickHandler);
        }
    });
    
    // 鼠标移动时更新工具提示位置
    document.addEventListener('mousemove', function(event) {
        const tooltip = document.getElementById('tooltip');
        if (tooltip && tooltip.style.display === 'block') {
            const mouseX = event.clientX;
            const mouseY = event.clientY;
            
            tooltip.style.left = (mouseX - tooltip.offsetWidth / 2) + 'px';
            tooltip.style.top = (mouseY - tooltip.offsetHeight - 15) + 'px';
            
            // 边界检查
            const rect = tooltip.getBoundingClientRect();
            if (rect.left < 10) {
                tooltip.style.left = '10px';
            }
            if (rect.right > window.innerWidth - 10) {
                tooltip.style.left = (window.innerWidth - tooltip.offsetWidth - 10) + 'px';
            }
            if (rect.top < 10) {
                tooltip.style.top = (mouseY + 15) + 'px';
            }
        }
    });
    
         // ESC键关闭弹窗和绘制模式
     document.addEventListener('keydown', function(event) {
         if (event.key === 'Escape') {
             closeModal();
             closeHotspotInfoModal(); // 关闭热点信息编辑模态框
             if (isDrawingMode) {
                 stopDrawingMode();
                 // 重置按钮状态
                 const drawingButton = document.getElementById('drawingButton');
                 if (drawingButton) {
                     drawingButton.textContent = '🎨 绘制新热点';
                     drawingButton.style.background = '#ff6b35';
                 }
             }

         }
     });
    
    // 为图片添加绘制热点功能
    const images = document.querySelectorAll('.image-container img');
    images.forEach(img => {
        img.addEventListener('mousedown', function(event) {
            if (!isDrawingMode || isSelecting) return; // 如果正在框选，则不绘制热点
            
            event.preventDefault();
            const rect = img.getBoundingClientRect();
            const x = Math.round(event.clientX - rect.left);
            const y = Math.round(event.clientY - rect.top);
            
            drawingStartPoint = { x, y };
            currentDrawingImage = img;
            
            // 创建临时绘制框
            const tempBox = document.createElement('div');
            tempBox.id = 'temp-drawing-box';
            tempBox.style.cssText = `
                position: fixed;
                left: ${rect.left + x}px;
                top: ${rect.top + y}px;
                width: 0;
                height: 0;
                border: 2px dashed #ffc107;
                background: rgba(255, 193, 7, 0.2);
                pointer-events: none;
                z-index: 1000;
                box-sizing: border-box;
            `;
            document.body.appendChild(tempBox);
        });
        
        img.addEventListener('mousemove', function(event) {
            if (!isDrawingMode || !drawingStartPoint || !currentDrawingImage) return;
            
            const rect = currentDrawingImage.getBoundingClientRect();
            const x = Math.round(event.clientX - rect.left);
            const y = Math.round(event.clientY - rect.top);
            
            const tempBox = document.getElementById('temp-drawing-box');
            if (tempBox) {
                const startX = Math.min(drawingStartPoint.x, x);
                const startY = Math.min(drawingStartPoint.y, y);
                const width = Math.abs(x - drawingStartPoint.x);
                const height = Math.abs(y - drawingStartPoint.y);
                
                tempBox.style.left = (rect.left + startX) + 'px';
                tempBox.style.top = (rect.top + startY) + 'px';
                tempBox.style.width = width + 'px';
                tempBox.style.height = height + 'px';
                
                // 检查是否达到最小尺寸要求
                const minSize = 5;
                const meetsSizeRequirement = width >= minSize && height >= minSize;
                
                // 根据尺寸要求改变预览框样式
                if (meetsSizeRequirement) {
                    tempBox.style.borderColor = '#28a745'; // 绿色表示可以创建
                    tempBox.style.backgroundColor = 'rgba(40, 167, 69, 0.2)';
                } else {
                    tempBox.style.borderColor = '#ffc107'; // 黄色表示太小
                    tempBox.style.backgroundColor = 'rgba(255, 193, 7, 0.2)';
                }
                
                // 显示尺寸信息和状态
                const status = meetsSizeRequirement ? '✓ 可创建' : `需要 ${minSize}×${minSize}`;
                tempBox.setAttribute('title', `${width} × ${height} 像素 - ${status}`);
            }
        });
        
        img.addEventListener('mouseup', function(event) {
            if (!isDrawingMode || !drawingStartPoint || !currentDrawingImage) return;
            
            const rect = currentDrawingImage.getBoundingClientRect();
            const x = Math.round(event.clientX - rect.left);
            const y = Math.round(event.clientY - rect.top);
            
            // 移除临时绘制框
            const tempBox = document.getElementById('temp-drawing-box');
            if (tempBox) {
                tempBox.remove();
            }
            
            // 计算热点坐标
            const startX = Math.min(drawingStartPoint.x, x);
            const startY = Math.min(drawingStartPoint.y, y);
            const endX = Math.max(drawingStartPoint.x, x);
            const endY = Math.max(drawingStartPoint.y, y);
            
            // 检查拖动区域大小，防止误创建热点
            const width = endX - startX;
            const height = endY - startY;
            const minSize = 5; // 最小5像素
            
            if (width >= minSize && height >= minSize) {
                // 创建新热点
                createNewHotspot(currentDrawingImage, startX, startY, endX, endY);
            } else {
                console.log(`拖动区域太小 (${width}×${height})，需要至少 ${minSize}×${minSize} 像素才能创建热点`);
                showInfo(`拖动区域太小\n\n需要拖动至少 ${minSize}×${minSize} 像素的区域才能创建热点。\n当前区域：${width}×${height} 像素`);
            }
            
            drawingStartPoint = null;
            currentDrawingImage = null;
        });
    });
    
         // 点击弹窗背景关闭弹窗
     document.addEventListener('click', function(event) {
         const modal = document.getElementById('modal');
         if (modal && event.target === modal) {
             closeModal();
         }
         
         // 点击热点信息编辑模态框背景关闭
         const hotspotInfoModal = document.getElementById('hotspotInfoModal');
         if (hotspotInfoModal && event.target === hotspotInfoModal) {
             closeHotspotInfoModal();
         }
     });
}

// 为热点添加编辑功能
function addDeleteButtonsToHotspots() {
    const hotspotAreas = document.querySelectorAll('.hotspot-area');
    hotspotAreas.forEach(area => {
        // 检查是否已经有删除按钮
        if (!area.querySelector('.delete-btn')) {
            const deleteBtn = document.createElement('div');
            deleteBtn.className = 'delete-btn';
            deleteBtn.innerHTML = '×';
            deleteBtn.title = '删除热点';
            
            // 添加删除事件
            deleteBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                const href = area.getAttribute('data-href');
                deleteHotspotFromDrawing(href);
            });
            
            area.appendChild(deleteBtn);
        }
        
        // 检查是否已经有调节手柄
        if (!area.querySelector('.resize-handle')) {
            // 添加四个调节手柄
            const handles = ['nw', 'ne', 'sw', 'se'];
            handles.forEach(position => {
                const handle = document.createElement('div');
                handle.className = `resize-handle ${position}`;
                handle.addEventListener('mousedown', function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                    startResizeHotspot(area, position, e);
                });
                area.appendChild(handle);
            });
        }
        
        // 添加双击编辑事件（避免重复添加）
        if (!area.hasAttribute('data-dblclick-added')) {
            area.addEventListener('dblclick', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const href = area.getAttribute('data-href');
                editHotspotFromDrawing(href);
            });
            area.setAttribute('data-dblclick-added', 'true');
        }
        
        // 添加拖拽移动功能（避免重复添加）
        if (!area.hasAttribute('data-drag-added')) {
            area.addEventListener('mousedown', function(e) {
                // 检查是否点击的是删除按钮
                if (e.target.classList.contains('delete-btn')) return;
                e.preventDefault();
                e.stopPropagation();
                const href = area.getAttribute('data-href');
                
                // 计算鼠标相对于热点的偏移
                const rect = area.getBoundingClientRect();
                dragOffset.x = e.clientX - rect.left;
                dragOffset.y = e.clientY - rect.top;
                
                startMoveHotspot(href, area);
            });
            area.setAttribute('data-drag-added', 'true');
        }
    });
}

// 移除热点编辑功能
function removeDeleteButtonsFromHotspots() {
    const deleteButtons = document.querySelectorAll('.delete-btn');
    deleteButtons.forEach(btn => btn.remove());
    
    const resizeHandles = document.querySelectorAll('.resize-handle');
    resizeHandles.forEach(handle => handle.remove());
    
    // 清理事件标记
    const hotspotAreas = document.querySelectorAll('.hotspot-area');
    hotspotAreas.forEach(area => {
        area.removeAttribute('data-dblclick-added');
        area.removeAttribute('data-drag-added');
    });
}

// 从绘制模式删除热点
function deleteHotspotFromDrawing(href) {
    showConfirm(`确定要删除热点 ${href} 吗？`, () => {
        console.log('删除热点:', href);
        
        // 从数据中删除
        delete hotspotInfo[href];
        console.log('从hotspotInfo中删除:', href);
        
        // 从imageData中删除热点
        imageData.images.forEach(image => {
            const hotspotIndex = image.hotspots.findIndex(h => h.href === href);
            if (hotspotIndex !== -1) {
                image.hotspots.splice(hotspotIndex, 1);
                console.log('从imageData中删除热点:', href, '从图片', image.id);
            }
        });
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 从页面中移除对应的热点区域
        const hotspotArea = document.querySelector(`[data-href="${href}"]`);
        if (hotspotArea) {
            hotspotArea.remove();
            console.log('从页面中删除热点区域:', href);
        } else {
            console.warn('未找到热点区域:', href);
        }
        
        // 从map中移除对应的area
        const area = document.querySelector(`area[href="${href}"]`);
        if (area) {
            area.remove();
            console.log('从map中删除area:', href);
        } else {
            console.warn('未找到area标签:', href);
        }
        
        // 重新同步数据到页面，确保数据一致性
        if (dataManager) {
            dataManager.syncDataToPage();
            // 重新初始化事件监听器
            if (typeof initEventListeners === 'function') {
                initEventListeners();
            }
        }
        
        showSuccess('热点已删除！');
    });
}

// 全局变量用于存储当前编辑的热点
let currentEditingHotspot = null;

// 框选相关变量
let isSelecting = false;
let selectionStartX = 0;
let selectionStartY = 0;
let selectedHotspots = new Set();
let isCtrlPressed = false;



// 开始移动热点
function startMoveHotspot(href, hotspotArea) {
    // 检查是否在绘制模式下
    if (!isDrawingMode) {
        showInfo('💡 提示：需要先进入绘制模式才能拖动热点\n\n右键点击选择"画热点"进入绘制模式', 3000);
        return;
    }
    
    console.log('开始移动热点:', href);
    currentMovingHotspot = href;
    isMovingHotspot = true;
    
    // 记录移动开始状态
    const area = document.querySelector(`area[href="${href}"]`);
    const startCoords = area ? area.getAttribute('coords') : null;
    
    logger.log('move', 'hotspot', {
        message: `开始移动热点: ${href}`,
        href: href,
        action: 'start',
        startCoords: startCoords,
        level: 'debug'
    });
    
    // 添加移动样式
    hotspotArea.classList.add('moving-hotspot');
    
    // 设置鼠标事件
    document.addEventListener('mousemove', moveHotspotHandler);
    document.addEventListener('mouseup', stopMoveHotspotHandler);
    
    // 阻止默认选择
    document.body.style.userSelect = 'none';
    
    console.log('热点移动模式已启动');
}

// 移动热点处理函数
function moveHotspotHandler(e) {
    if (!currentMovingHotspot || !isDrawingMode) return;
    
    e.preventDefault();
    e.stopPropagation();
    
    const hotspotArea = document.querySelector(`[data-href="${currentMovingHotspot}"]`);
    if (!hotspotArea) return;
    
    const imageContainer = hotspotArea.closest('.image-container');
    const img = imageContainer.querySelector('img');
    if (!img) return;
    
    const rect = img.getBoundingClientRect();
    
    // 计算鼠标相对于图片的位置
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    
    // 获取热点尺寸
    const hotspotWidth = hotspotArea.offsetWidth;
    const hotspotHeight = hotspotArea.offsetHeight;
    
    // 使用记录的偏移量计算新位置，确保不超出图片边界
    const newX = Math.max(0, Math.min(mouseX - dragOffset.x, img.offsetWidth - hotspotWidth));
    const newY = Math.max(0, Math.min(mouseY - dragOffset.y, img.offsetHeight - hotspotHeight));
    
    // 更新热点位置
    hotspotArea.style.left = newX + 'px';
    hotspotArea.style.top = newY + 'px';
    
    // 更新area元素的coords属性
    const area = document.querySelector(`area[href="${currentMovingHotspot}"]`);
    if (area) {
        const coords = `${Math.round(newX)},${Math.round(newY)},${Math.round(newX + hotspotWidth)},${Math.round(newY + hotspotHeight)}`;
        area.setAttribute('coords', coords);
    }
    
    // 移动过程中不输出日志以提高性能
}

// 停止移动热点处理函数
async function stopMoveHotspotHandler() {
    if (!currentMovingHotspot || !isDrawingMode) return;
    
    const hotspotArea = document.querySelector(`[data-href="${currentMovingHotspot}"]`);
    if (hotspotArea) {
        hotspotArea.classList.remove('moving-hotspot');
    }
    
    // 更新imageData中的坐标
    const area = document.querySelector(`area[href="${currentMovingHotspot}"]`);
    if (area) {
        const coords = area.getAttribute('coords');
        
        // 更新imageData
        imageData.images.forEach(image => {
            const hotspot = image.hotspots.find(h => h.href === currentMovingHotspot);
            if (hotspot) {
                hotspot.coords = coords;
                console.log('更新热点坐标:', currentMovingHotspot, coords);
            }
        });
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 如果服务器在线，同步到服务器
        if (serverOnline) {
            try {
                const response = await fetch('/update-hotspot-coords', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        href: currentMovingHotspot,
                        coords: coords
                    })
                });
                const result = await response.json();
                if (result.success) {
                    console.log('服务器坐标更新成功');
                } else {
                    console.warn('服务器坐标更新失败:', result.message);
                }
            } catch (error) {
                console.error('服务器坐标更新失败:', error);
            }
        }
    }
    
    // 清理事件监听器
    document.removeEventListener('mousemove', moveHotspotHandler);
    document.removeEventListener('mouseup', stopMoveHotspotHandler);
    
    // 恢复文本选择
    document.body.style.userSelect = '';
    
    const finalCoords = area ? area.getAttribute('coords') : 'unknown';
    console.log(`热点 ${currentMovingHotspot} 移动完成，新坐标: ${finalCoords}`);
    
    // 记录移动完成日志
    logger.log('move', 'hotspot', {
        message: `热点移动完成: ${currentMovingHotspot}`,
        href: currentMovingHotspot,
        action: 'complete',
        finalCoords: finalCoords,
        level: 'info'
    });
    
    currentMovingHotspot = null;
    isMovingHotspot = false;
    dragOffset = { x: 0, y: 0 }; // 重置偏移量
    
    // 重新同步数据到页面，确保数据一致性
    if (dataManager) {
        dataManager.syncDataToPage();
        // 重新初始化事件监听器
        if (typeof initEventListeners === 'function') {
            initEventListeners();
        }
    }
}

// 调节热点大小的相关变量
let isResizingHotspot = false;
let currentResizingHotspot = null;
let resizeStartPoint = null;
let resizeDirection = null;
let originalHotspotRect = null;

// 开始调节热点大小
function startResizeHotspot(hotspotArea, direction, event) {
    console.log('开始调节热点大小:', direction);
    isResizingHotspot = true;
    currentResizingHotspot = hotspotArea;
    resizeDirection = direction;
    
    // 记录起始点
    resizeStartPoint = { x: event.clientX, y: event.clientY };
    
    // 记录原始热点矩形
    const rect = hotspotArea.getBoundingClientRect();
    const imageContainer = hotspotArea.closest('.image-container');
    const img = imageContainer.querySelector('img');
    const imgRect = img.getBoundingClientRect();
    
    originalHotspotRect = {
        left: parseInt(hotspotArea.style.left),
        top: parseInt(hotspotArea.style.top),
        width: parseInt(hotspotArea.style.width),
        height: parseInt(hotspotArea.style.height)
    };
    
    // 添加调节样式
    hotspotArea.classList.add('resizing-hotspot');
    
    // 设置事件监听器
    document.addEventListener('mousemove', resizeHotspotHandler);
    document.addEventListener('mouseup', stopResizeHotspotHandler);
    
    // 阻止默认选择
    document.body.style.userSelect = 'none';
    
    console.log('热点调节模式已启动');
}

// 调节热点处理函数
function resizeHotspotHandler(event) {
    if (!isResizingHotspot || !currentResizingHotspot) return;
    
    const deltaX = event.clientX - resizeStartPoint.x;
    const deltaY = event.clientY - resizeStartPoint.y;
    
    let newLeft = originalHotspotRect.left;
    let newTop = originalHotspotRect.top;
    let newWidth = originalHotspotRect.width;
    let newHeight = originalHotspotRect.height;
    
    // 根据调节方向计算新的位置和大小
    switch (resizeDirection) {
        case 'nw': // 左上角
            newLeft = originalHotspotRect.left + deltaX;
            newTop = originalHotspotRect.top + deltaY;
            newWidth = originalHotspotRect.width - deltaX;
            newHeight = originalHotspotRect.height - deltaY;
            break;
        case 'ne': // 右上角
            newTop = originalHotspotRect.top + deltaY;
            newWidth = originalHotspotRect.width + deltaX;
            newHeight = originalHotspotRect.height - deltaY;
            break;
        case 'sw': // 左下角
            newLeft = originalHotspotRect.left + deltaX;
            newWidth = originalHotspotRect.width - deltaX;
            newHeight = originalHotspotRect.height + deltaY;
            break;
        case 'se': // 右下角
            newWidth = originalHotspotRect.width + deltaX;
            newHeight = originalHotspotRect.height + deltaY;
            break;
    }
    
    // 限制最小尺寸
    const minSize = 10;
    if (newWidth < minSize) {
        if (resizeDirection.includes('w')) newLeft = originalHotspotRect.left + originalHotspotRect.width - minSize;
        newWidth = minSize;
    }
    if (newHeight < minSize) {
        if (resizeDirection.includes('n')) newTop = originalHotspotRect.top + originalHotspotRect.height - minSize;
        newHeight = minSize;
    }
    
    // 限制边界
    if (newLeft < 0) {
        newWidth += newLeft;
        newLeft = 0;
    }
    if (newTop < 0) {
        newHeight += newTop;
        newTop = 0;
    }
    
    // 应用新的位置和大小
    currentResizingHotspot.style.left = newLeft + 'px';
    currentResizingHotspot.style.top = newTop + 'px';
    currentResizingHotspot.style.width = newWidth + 'px';
    currentResizingHotspot.style.height = newHeight + 'px';
    
    // 更新对应的area标签坐标
    const href = currentResizingHotspot.getAttribute('data-href');
    const area = document.querySelector(`area[href="${href}"]`);
    if (area) {
        const coords = `${newLeft},${newTop},${newLeft + newWidth},${newTop + newHeight}`;
        area.setAttribute('coords', coords);
    }
}

// 停止调节热点大小
async function stopResizeHotspotHandler() {
    if (!isResizingHotspot || !currentResizingHotspot) return;
    
    // 移除调节样式
    currentResizingHotspot.classList.remove('resizing-hotspot');
    
    // 更新imageData中的坐标
    const href = currentResizingHotspot.getAttribute('data-href');
    const area = document.querySelector(`area[href="${href}"]`);
    if (area) {
        const coords = area.getAttribute('coords');
        
        // 更新imageData
        imageData.images.forEach(image => {
            const hotspot = image.hotspots.find(h => h.href === href);
            if (hotspot) {
                hotspot.coords = coords;
                console.log('更新热点坐标:', href, coords);
            }
        });
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 如果服务器在线，同步到服务器
        if (serverOnline) {
            try {
                const response = await fetch('/update-hotspot-coords', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        href: href,
                        coords: coords
                    })
                });
                const result = await response.json();
                if (result.success) {
                    console.log('服务器坐标更新成功');
                } else {
                    console.warn('服务器坐标更新失败:', result.message);
                }
            } catch (error) {
                console.error('服务器坐标更新失败:', error);
            }
        }
    }
    
    // 清理事件监听器
    document.removeEventListener('mousemove', resizeHotspotHandler);
    document.removeEventListener('mouseup', stopResizeHotspotHandler);
    
    // 恢复文本选择
    document.body.style.userSelect = '';
    
    isResizingHotspot = false;
    currentResizingHotspot = null;
    resizeStartPoint = null;
    resizeDirection = null;
    originalHotspotRect = null;
    
    console.log('热点调节完成');
}

// 从绘制模式编辑热点
function editHotspotFromDrawing(href) {
    console.log('editHotspotFromDrawing 被调用，href:', href);
    currentEditingHotspot = href;
    console.log('设置 currentEditingHotspot:', currentEditingHotspot);
    
    const currentInfo = hotspotInfo[href] || '';
    console.log('当前热点信息:', currentInfo);
    
    // 显示编辑模态框
    const modal = document.getElementById('hotspotInfoModal');
    const textarea = document.getElementById('hotspotInfoTextarea');
    
    console.log('modal:', modal);
    console.log('textarea:', textarea);
    
    if (modal && textarea) {
        textarea.value = currentInfo;
        modal.style.display = 'block';
        // 聚焦到文本框
        setTimeout(() => {
            textarea.focus();
            textarea.select();
        }, 100);
        console.log('模态框已显示');
    } else {
        console.error('模态框或文本框未找到');
    }
}

// 关闭热点信息编辑模态框
function closeHotspotInfoModal() {
    console.log('closeHotspotInfoModal 被调用');
    const modal = document.getElementById('hotspotInfoModal');
    if (modal) {
        modal.style.display = 'none';
        currentEditingHotspot = null;
        console.log('模态框已关闭，currentEditingHotspot 已重置');
    } else {
        console.error('模态框未找到');
    }
}

// 保存热点信息
function saveHotspotInfo() {
    console.log('saveHotspotInfo 被调用');
    console.log('currentEditingHotspot:', currentEditingHotspot);
    
    const textarea = document.getElementById('hotspotInfoTextarea');
    console.log('textarea:', textarea);
    
    if (!textarea || !currentEditingHotspot) {
        console.error('保存失败：textarea或currentEditingHotspot为空');
        showError('保存失败！');
        return;
    }
    
    const newInfo = textarea.value.trim();
    console.log('新的热点信息:', newInfo);
    
    if (newInfo) {
        hotspotInfo[currentEditingHotspot] = newInfo;
        console.log('热点信息已保存到 hotspotInfo:', hotspotInfo[currentEditingHotspot]);
        
        // 标记数据已更改
        if (dataManager) {
            dataManager.markDataChanged();
        }
        
        // 重新初始化事件监听器，确保悬浮提示使用最新的信息
        initEventListeners();
        
        showSuccess('热点信息已更新！');
        closeHotspotInfoModal();
    } else {
        console.error('备注信息为空');
        showWarning('备注信息不能为空！');
    }
}

// 创建新热点
function createNewHotspot(img, startX, startY, endX, endY) {
    const href = `#${nextHotspotId}`;
    const coords = `${startX},${startY},${endX},${endY}`;
    
    // 记录操作前状态
    const beforeState = {
        nextHotspotId: nextHotspotId,
        hotspotExists: false
    };
    
    // 添加热点信息
    hotspotInfo[href] = `新热点区域${nextHotspotId}\n具体信息待补充`;
    
    // 找到对应的图片容器
    const imageContainer = img.closest('.image-container');
    const imageId = parseInt(imageContainer.getAttribute('data-image-id'));
    
    // 更新imageData中的热点信息
    const imageIndex = imageData.images.findIndex(img => img.id === imageId);
    if (imageIndex !== -1) {
        imageData.images[imageIndex].hotspots.push({
            id: nextHotspotId,
            coords: coords,
            href: href
        });
    }
    
    // 标记数据已更改
    if (dataManager) {
        dataManager.markDataChanged();
    }
    
    const map = imageContainer.querySelector('map');
    const overlay = imageContainer.querySelector('.hotspot-overlay');
    
    // 添加area标签
    const area = document.createElement('area');
    area.setAttribute('shape', 'rect');
    area.setAttribute('coords', coords);
    area.setAttribute('href', href);
    map.appendChild(area);
    
    // 添加热点可视化区域
    const hotspotArea = document.createElement('div');
    hotspotArea.className = 'hotspot-area';
    hotspotArea.setAttribute('data-href', href);
    // 使用单独的样式设置，避免cssText可能的问题
    hotspotArea.style.left = `${startX}px`;
    hotspotArea.style.top = `${startY}px`;
    hotspotArea.style.width = `${endX - startX}px`;
    hotspotArea.style.height = `${endY - startY}px`;
    overlay.appendChild(hotspotArea);
    
    // 重新初始化事件监听器
    initEventListeners();
    
    // 如果在编辑模式下，为新热点添加编辑功能
    if (isDrawingMode) {
        addDeleteButtonsToHotspots();
    }
    
    // 重新同步数据到页面，确保数据一致性
    if (dataManager) {
        dataManager.syncDataToPage();
        // 重新初始化事件监听器
        if (typeof initEventListeners === 'function') {
            initEventListeners();
        }
    }
    
    nextHotspotId++;
    
    // 记录操作后状态和日志
    const afterState = {
        nextHotspotId: nextHotspotId,
        hotspotExists: true,
        href: href,
        coords: coords,
        imageId: imageId,
        hotspotInfo: hotspotInfo[href]
    };
    
    // 记录操作日志
    logger.log('create', 'hotspot', {
        message: `创建热点 ${href}`,
        href: href,
        coords: coords,
        imageId: imageId,
        size: {
            width: endX - startX,
            height: endY - startY
        },
        level: 'info'
    }, beforeState, afterState);
    
    // 根据当前模式决定是否自动退出绘制模式
    if (!isContinuousDrawMode) {
        // 非连续绘画模式：自动退出绘制模式，返回选择模式
        stopDrawingMode();
        
        // 提示用户热点创建成功
        setTimeout(() => {
            showSuccess(`热点 #${nextHotspotId-1} 创建成功！\n\n已自动返回选择模式\n你可以：\n1. 左键拖动框选热点\n2. 右键菜单进行操作\n3. 双击热点编辑备注信息`, 3000);
        }, 100);
    } else {
        // 连续绘画模式：保持绘制模式，显示简短提示
        setTimeout(() => {
            showSuccess(`热点 #${nextHotspotId-1} 创建成功！\n\n连续绘画模式：继续绘制更多热点\n松开Ctrl键退出绘画模式`, 2000);
        }, 100);
    }
}

// 测试热点信息保存功能
function testHotspotInfo() {
    console.log('=== 测试热点信息 ===');
    console.log('当前所有热点信息:', hotspotInfo);
    console.log('热点信息数量:', Object.keys(hotspotInfo).length);
    
    // 显示前几个热点的信息
    const keys = Object.keys(hotspotInfo);
    for (let i = 0; i < Math.min(5, keys.length); i++) {
        const key = keys[i];
        console.log(`${key}:`, hotspotInfo[key]);
    }
    
    // 测试悬浮提示更新
    console.log('=== 测试悬浮提示更新 ===');
    const hotspotAreas = document.querySelectorAll('.hotspot-area');
    hotspotAreas.forEach((area, index) => {
        const href = area.getAttribute('data-href');
        const info = hotspotInfo[href];
        console.log(`热点区域 ${index + 1} (${href}):`, info ? '有信息' : '无信息');
    });
    
    showInfo(`热点信息测试完成！\n\n当前共有 ${keys.length} 个热点\n悬浮提示已重新绑定\n详细信息请查看浏览器控制台`);
}

// 保存所有数据到localStorage和项目文件
async function saveAllData() {
    if (dataManager) {
        // 保存到localStorage
        const localStorageSuccess = dataManager.saveData();
        
        if (offlineMode) {
            if (localStorageSuccess) {
                showSuccess('数据已保存到本地存储！\n\n当前处于离线模式，数据已保存到浏览器。\n服务器恢复后，数据将自动同步到项目文件。');
            } else {
                showError('保存失败！请检查浏览器存储空间或尝试刷新页面。');
            }
            return;
        }
        
        // 保存到项目文件（通过Python服务器）
        const fileSuccess = await saveToProjectFile();
        
        if (localStorageSuccess && fileSuccess) {
            showSuccess('所有数据已保存！\n\n保存位置：\n• 浏览器本地存储（用于页面刷新）\n• 项目目录：map_hotspots_data.json\n\n数据会自动保存，下次打开网页时会自动加载。');
        } else if (localStorageSuccess) {
            showWarning('部分保存成功！\n\n✅ 已保存到浏览器本地存储\n❌ 保存到项目文件失败\n\n数据已保存到浏览器，页面刷新后会保留。');
        } else {
            showError('保存失败！请检查浏览器存储空间或尝试刷新页面。');
        }
    } else {
        showError('数据管理器未初始化！请刷新页面重试。');
    }
}

// 保存到项目文件（通过Python服务器）
async function saveToProjectFile() {
    try {
        // 准备保存的数据
        const saveData = {
            imageData: imageData,
            hotspotInfo: hotspotInfo,
            hotspotNames: hotspotNames,
            nextHotspotId: nextHotspotId
        };
        
        // 发送到Python服务器
        const response = await fetch('/save-data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(saveData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            console.log('数据已保存到项目文件:', result.message);
            return true;
        } else {
            console.error('保存到项目文件失败:', result.message);
            return false;
        }
    } catch (error) {
        console.error('保存到项目文件失败:', error);
        return false;
    }
}



// JSON导出功能
function saveToJson() {
    // 准备保存的数据
    const saveData = {
        imageData: imageData,
        hotspotInfo: hotspotInfo,
        hotspotNames: hotspotNames,
        nextHotspotId: nextHotspotId,
        lastUpdated: new Date().toISOString()
    };
    
    // 创建下载链接
    const dataStr = JSON.stringify(saveData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = 'map_hotspots_data.json';
    link.click();
    
    URL.revokeObjectURL(url);
    showSuccess('数据已导出到 map_hotspots_data.json 文件！');
}

// 检查服务器状态
async function checkServerStatus() {
    try {
        const response = await fetch('/server-status');
        const result = await response.json();
        
        if (result.success) {
            serverOnline = true;
            offlineMode = false;
            updateServerStatus('在线', '#28a745');
        } else {
            serverOnline = false;
            offlineMode = true;
            updateServerStatus('离线', '#dc3545');
        }
    } catch (error) {
        serverOnline = false;
        offlineMode = true;
        updateServerStatus('离线', '#dc3545');
        console.log('服务器离线，进入离线模式');
        
        // 只在首次检查时显示错误
        if (!window.serverStatusChecked) {
            showError('服务器连接失败');
            window.serverStatusChecked = true;
        }
    }
}

// 更新服务器状态显示
function updateServerStatus(status, color) {
    const statusElement = document.getElementById('serverStatus');
    if (statusElement) {
        statusElement.textContent = status;
        statusElement.style.color = color;
        statusElement.style.fontWeight = status === '离线' ? 'bold' : 'normal';
    }
}

// 显示错误状态（已弃用，现在使用Toast）
function showErrorOld(message) {
    const errorElement = document.getElementById('errorStatus');
    if (errorElement) {
        errorElement.textContent = `⚠️ ${message}`;
        errorElement.style.display = 'inline';
        errorElement.style.color = '#dc3545';
        errorElement.style.fontWeight = 'bold';
        
        // 5秒后自动隐藏
        setTimeout(() => {
            errorElement.style.display = 'none';
        }, 5000);
    }
}

// 隐藏错误状态
function hideError() {
    const errorElement = document.getElementById('errorStatus');
    if (errorElement) {
        errorElement.style.display = 'none';
    }
}

// 显示备份管理器
async function showBackupManager() {
    document.getElementById('backupManagerModal').style.display = 'block';
    await refreshBackupList();
}

// 关闭备份管理器
function closeBackupManager() {
    document.getElementById('backupManagerModal').style.display = 'none';
}

// 刷新备份列表
async function refreshBackupList() {
    const backupList = document.getElementById('backupList');
    
    if (!serverOnline) {
        backupList.innerHTML = '<p style="color: #dc3545;">❌ 服务器离线，无法访问备份</p>';
        return;
    }
    
    try {
        backupList.innerHTML = '<p>正在加载备份列表...</p>';
        
        const response = await fetch('/list-backups');
        const result = await response.json();
        
        if (result.success) {
            if (result.backups.length === 0) {
                backupList.innerHTML = '<p>暂无备份文件</p>';
            } else {
                let html = '<div style="max-height: 300px; overflow-y: auto;">';
                result.backups.forEach(backup => {
                    const size = (backup.size / 1024).toFixed(1);
                    const date = new Date(backup.modified).toLocaleString();
                    html += `
                        <div style="border: 1px solid #ddd; margin: 5px 0; padding: 10px; border-radius: 5px;">
                            <div><strong>${backup.filename}</strong></div>
                            <div style="font-size: 12px; color: #666;">
                                大小: ${size}KB | 修改时间: ${date}
                            </div>
                            <button class="btn btn-primary" style="margin-top: 5px;" 
                                    onclick="restoreBackup('${backup.filename}')">
                                恢复此备份
                            </button>
                        </div>
                    `;
                });
                html += '</div>';
                backupList.innerHTML = html;
            }
        } else {
            backupList.innerHTML = `<p style="color: #dc3545;">❌ 加载备份列表失败: ${result.message}</p>`;
        }
    } catch (error) {
        backupList.innerHTML = '<p style="color: #dc3545;">❌ 网络错误，无法加载备份列表</p>';
    }
}



// 自定义弹窗函数
function showCustomModal(title, message, type = 'info', buttons = []) {
    const modal = document.getElementById('customModal');
    const modalTitle = document.getElementById('customModalTitle');
    const modalBody = document.getElementById('customModalBody');
    const modalFooter = document.getElementById('customModalFooter');
    
    // 设置标题和内容
    modalTitle.textContent = title;
    modalBody.textContent = message;
    
    // 根据类型设置图标和样式
    let icon = '';
    let titleClass = '';
    
    switch(type) {
        case 'success':
            icon = '✅';
            titleClass = 'custom-modal-success';
            break;
        case 'error':
            icon = '❌';
            titleClass = 'custom-modal-error';
            break;
        case 'warning':
            icon = '⚠️';
            titleClass = 'custom-modal-warning';
            break;
        case 'info':
        default:
            icon = 'ℹ️';
            titleClass = 'custom-modal-info';
            break;
    }
    
    // 设置标题样式
    modalTitle.className = `custom-modal-title ${titleClass}`;
    modalTitle.innerHTML = `${icon} ${title}`;
    
    // 设置按钮
    modalFooter.innerHTML = '';
    if (buttons.length === 0) {
        // 默认按钮
        const okBtn = document.createElement('button');
        okBtn.className = 'custom-modal-btn custom-modal-btn-primary';
        okBtn.textContent = '确定';
        okBtn.onclick = closeCustomModal;
        modalFooter.appendChild(okBtn);
    } else {
        buttons.forEach(btn => {
            const button = document.createElement('button');
            button.className = `custom-modal-btn custom-modal-btn-${btn.type || 'primary'}`;
            button.textContent = btn.text;
            button.onclick = btn.onclick || closeCustomModal;
            modalFooter.appendChild(button);
        });
    }
    
    // 显示弹窗
    modal.style.display = 'block';
    
    // 点击背景关闭
    modal.onclick = function(e) {
        if (e.target === modal) {
            closeCustomModal();
        }
    };
    
    // ESC键关闭
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.style.display === 'block') {
            closeCustomModal();
        }
    });
}

function closeCustomModal() {
    const modal = document.getElementById('customModal');
    modal.style.display = 'none';
}

// Toast提示函数
let toastIdCounter = 0;

function showToast(message, type = 'info', duration = 2000) {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    
    const toastId = `toast-${toastIdCounter++}`;
    const toast = document.createElement('div');
    toast.id = toastId;
    toast.className = `toast toast-${type}`;
    
    const icons = {
        success: '✅',
        error: '❌', 
        warning: '⚠️',
        info: 'ℹ️'
    };
    
    toast.innerHTML = `
        <div class="toast-icon">${icons[type] || icons.info}</div>
        <div class="toast-content">${message}</div>
        <button class="toast-close" onclick="hideToast('${toastId}')" title="关闭">×</button>
    `;
    
    container.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        hideToast(toastId);
    }, duration);
    
    return toastId;
}

function hideToast(toastId) {
    const toast = document.getElementById(toastId);
    if (!toast) return;
    
    toast.classList.add('hide');
    
    // 移除DOM元素
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 300);
}

// 简化的提示函数
function showSuccess(message, duration = 2000) {
    return showToast(message, 'success', duration);
}

function showError(message, duration = 2000) {
    return showToast(message, 'error', duration);
}

function showWarning(message, duration = 2000) {
    return showToast(message, 'warning', duration);
}

function showInfo(message, duration = 2000) {
    return showToast(message, 'info', duration);
}

// 框选功能
function initSelectionEvents() {
    // Ctrl键状态监听
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey) {
            isCtrlPressed = true;
            // 按下Ctrl键进入连续绘画模式
            if (!isContinuousDrawMode && isSelectionMode) {
                isContinuousDrawMode = true;
                startDrawingMode();
                showInfo('🎨 Ctrl连续绘画模式已启动\n\n• 可连续绘制多个热点\n• 松开Ctrl键退出绘画模式', 2000);
            }
        }
    });
    
    document.addEventListener('keyup', function(e) {
        if (!e.ctrlKey) {
            isCtrlPressed = false;
            // 松开Ctrl键退出连续绘画模式
            if (isContinuousDrawMode) {
                isContinuousDrawMode = false;
                stopDrawingMode();
                showInfo('📦 已退出连续绘画模式\n返回选择模式', 1500);
            }
        }
    });
    
    // 右键菜单功能
    document.addEventListener('contextmenu', function(e) {
        // 检查是否在图片容器内
        const imageContainer = e.target.closest('.image-container');
        if (!imageContainer) return;
        
        e.preventDefault();
        
        // 检查是否点击在热点上
        const hotspotArea = e.target.closest('.hotspot-area');
        if (hotspotArea) {
            const href = hotspotArea.getAttribute('data-href');
            
            // 如果当前没有任何选中的热点，则选中右键点击的热点
            if (selectedHotspots.size === 0) {
                selectHotspot(href);
            }
            // 如果已有选中的热点，保持当前选择状态不变
        }
        // 点击空白处不清除选择，保持当前选中状态
        
        showContextMenu(e.clientX, e.clientY);
    });
    
    // 框选开始
    document.addEventListener('mousedown', function(e) {
        if (e.button !== 0) return; // 只处理左键
        if (e.target.closest('.hotspot-area') || e.target.closest('.context-menu')) return;
        
        // 检查是否在图片容器内
        const imageContainer = e.target.closest('.image-container');
        if (imageContainer) {
            // 在选择模式下直接框选，在绘制模式下需要Ctrl键
            if (isSelectionMode || (isDrawingMode && isCtrlPressed)) {
                e.preventDefault();
                startSelection(e.clientX, e.clientY);
            }
        }
    });
    
    // 框选移动
    document.addEventListener('mousemove', function(e) {
        if (isSelecting) {
            updateSelection(e.clientX, e.clientY);
        }
    });
    
    // 框选结束
    document.addEventListener('mouseup', function(e) {
        if (isSelecting) {
            endSelection();
        }
    });
    
    // 点击空白处清除选择
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.hotspot-area') && !e.target.closest('.context-menu')) {
            clearSelection();
            hideContextMenu();
        }
    });
}

function startSelection(x, y) {
    isSelecting = true;
    selectionStartX = x;
    selectionStartY = y;
    
    const selectionBox = document.getElementById('selectionBox');
    selectionBox.style.left = x + 'px';
    selectionBox.style.top = y + 'px';
    selectionBox.style.width = '0px';
    selectionBox.style.height = '0px';
    selectionBox.style.display = 'block';
}

function updateSelection(x, y) {
    const selectionBox = document.getElementById('selectionBox');
    const left = Math.min(selectionStartX, x);
    const top = Math.min(selectionStartY, y);
    const width = Math.abs(x - selectionStartX);
    const height = Math.abs(y - selectionStartY);
    
    selectionBox.style.left = left + 'px';
    selectionBox.style.top = top + 'px';
    selectionBox.style.width = width + 'px';
    selectionBox.style.height = height + 'px';
}

function endSelection() {
    isSelecting = false;
    const selectionBox = document.getElementById('selectionBox');
    
    // 获取框选区域
    const rect = selectionBox.getBoundingClientRect();
    
    // 先检查框选区域是否有效（避免误操作）
    if (rect.width < 5 && rect.height < 5) {
        console.log('🚫 框选区域太小，忽略选择');
        selectionBox.style.display = 'none';
        return;
    }
    
    // 清除之前的选择
    clearSelection();
    
    // 检查哪些热点在框选区域内
    const hotspotAreas = document.querySelectorAll('.hotspot-area');
    console.log(`🔍 框选检查: 找到 ${hotspotAreas.length} 个热点区域`);
    
    let selectedCount = 0;
    const newlySelectedHotspots = [];
    
    hotspotAreas.forEach(area => {
        const hotspotRect = area.getBoundingClientRect();
        const href = area.getAttribute('data-href');
        
        // 检查热点是否与选择框重叠
        if (isOverlapping(rect, hotspotRect)) {
            newlySelectedHotspots.push(href);
            selectedCount++;
        }
    });
    
    // 隐藏选择框
    selectionBox.style.display = 'none';
    
    // 批量添加选中的热点（避免在添加过程中被清除）
    newlySelectedHotspots.forEach(href => {
        selectHotspot(href);
    });
    
    console.log(`📦 框选完成: 选中了 ${selectedCount} 个热点`, newlySelectedHotspots);
    
    // 显示选择结果
    if (selectedHotspots.size > 0) {
        showInfo(`✅ 已选择 ${selectedHotspots.size} 个热点\n\n• 选中的热点会显示橙色边框和脉动效果\n• 右键点击可进行批量操作\n• 左键点击空白处可取消选择`, 4000);
    }
}

function isOverlapping(rect1, rect2) {
    return !(rect1.right < rect2.left || 
             rect1.left > rect2.right || 
             rect1.bottom < rect2.top || 
             rect1.top > rect2.bottom);
}

function selectHotspot(href) {
    selectedHotspots.add(href);
    const hotspotArea = document.querySelector(`[data-href="${href}"]`);
    if (hotspotArea) {
        // 确保CSS类被正确添加
        hotspotArea.classList.add('selected-hotspot');
        
        // 立即设置内联样式作为备用方案
        hotspotArea.style.background = 'rgba(255, 140, 0, 0.6)';
        hotspotArea.style.border = '4px solid rgba(255, 140, 0, 1)';
        hotspotArea.style.boxShadow = '0 0 20px rgba(255, 140, 0, 0.8)';
        hotspotArea.style.zIndex = '150';
        hotspotArea.style.transform = 'scale(1.05)';
        hotspotArea.style.animation = 'pulse-selection 1.5s infinite';
        
        console.log(`✅ 选中热点: ${href} (强制设置样式)`);
        
        // 延迟验证样式是否正确应用
        setTimeout(() => {
            const hasClass = hotspotArea.classList.contains('selected-hotspot');
            const computedStyle = window.getComputedStyle(hotspotArea);
            console.log(`🎨 热点 ${href} 最终样式:`, {
                hasSelectedClass: hasClass,
                background: computedStyle.backgroundColor,
                borderColor: computedStyle.borderColor,
                borderWidth: computedStyle.borderWidth,
                zIndex: computedStyle.zIndex
            });
        }, 100);
    } else {
        console.warn(`❌ 未找到热点元素: ${href}`);
    }
}

function clearSelection() {
    console.log(`🧹 清除选择: 当前选中 ${selectedHotspots.size} 个热点`);
    selectedHotspots.forEach(href => {
        const hotspotArea = document.querySelector(`[data-href="${href}"]`);
        if (hotspotArea) {
            hotspotArea.classList.remove('selected-hotspot');
            // 强制清除内联样式
            hotspotArea.style.background = '';
            hotspotArea.style.border = '';
            hotspotArea.style.boxShadow = '';
            hotspotArea.style.zIndex = '';
            hotspotArea.style.transform = '';
            hotspotArea.style.animation = '';
            console.log(`🚮 清除热点选中状态: ${href}`);
        }
    });
    selectedHotspots.clear();
    console.log(`✨ 选择已清除，当前选中: ${selectedHotspots.size} 个热点`);
}

function selectAllHotspots() {
    clearSelection();
    const hotspotAreas = document.querySelectorAll('.hotspot-area');
    hotspotAreas.forEach(area => {
        const href = area.getAttribute('data-href');
        selectHotspot(href);
    });
    showInfo(`已选择所有 ${selectedHotspots.size} 个热点`);
}

function showContextMenu(x, y) {
    const contextMenu = document.getElementById('contextMenu');
    contextMenu.style.left = x + 'px';
    contextMenu.style.top = y + 'px';
    contextMenu.style.display = 'block';
    
    // 根据当前状态更新菜单项
    const drawBtn = document.getElementById('drawHotspot');
    const renameBtn = document.getElementById('renameHotspot');
    const deleteBtn = document.getElementById('deleteSelectedHotspots');
    const cancelBtn = document.getElementById('cancelSelection');
    
    // 根据是否有选中热点调整菜单显示
    if (selectedHotspots.size > 0) {
        // 重命名按钮只在选中单个热点时显示
        if (selectedHotspots.size === 1) {
            renameBtn.style.display = 'block';
        } else {
            renameBtn.style.display = 'none';
        }
        
        deleteBtn.style.display = 'block';
        deleteBtn.textContent = `🗑️ 删除选中热点 (${selectedHotspots.size})`;
        cancelBtn.style.display = 'block';
    } else {
        renameBtn.style.display = 'none';
        deleteBtn.style.display = 'none';
        cancelBtn.style.display = 'none';
    }
    
    // 绘制热点选项始终显示
    drawBtn.style.display = 'block';
}

function hideContextMenu() {
    const contextMenu = document.getElementById('contextMenu');
    contextMenu.style.display = 'none';
}

// 重命名选中的热点
function renameSelectedHotspot() {
    if (selectedHotspots.size === 0) {
        showWarning('请先选中一个热点！');
        return;
    }
    
    if (selectedHotspots.size > 1) {
        showWarning('只能为一个热点重命名，请选择单个热点！');
        return;
    }
    
    const hotspotHref = Array.from(selectedHotspots)[0];
    
    // 直接使用href作为hotspotId
    const hotspotId = hotspotHref;
    
    // 获取当前名称
    const currentName = hotspotNames[hotspotId] || `热点 - ${hotspotId}`;
    
    // 弹出输入框
    const newName = prompt(`请输入新的热点名称：`, currentName);
    
    if (newName === null) {
        // 用户取消
        return;
    }
    
    if (newName.trim() === '') {
        showWarning('热点名称不能为空！');
        return;
    }
    
    // 保存新名称
    hotspotNames[hotspotId] = newName.trim();
    
    // 更新相关窗口的标题
    updateWindowTitlesForHotspot(hotspotId, newName.trim());
    
    // 保存到服务器
    saveHotspotName(hotspotId, newName.trim());
    
    showSuccess(`热点已重命名为："${newName.trim()}"`);
    
    console.log(`✏️ 热点重命名: ${hotspotId} -> "${newName.trim()}"`);
}

// 更新指定热点相关窗口的标题
function updateWindowTitlesForHotspot(hotspotId, newName) {
    // 查找所有与此热点相关的窗口
    const windowManager = document.getElementById('windowManager');
    const windowItems = windowManager.querySelectorAll('.window-item');
    
    windowItems.forEach(item => {
        const windowId = item.getAttribute('data-window-id');
        
        // 检查窗口ID是否与热点相关（格式为 "hotspot_href"）
        if (windowId && windowId.startsWith('hotspot_') && windowId.includes(hotspotId)) {
            // 更新窗口项标题
            const titleSpan = item.querySelector('span');
            if (titleSpan) {
                titleSpan.textContent = newName;
            }
            
            // 更新模态框标题
            const modalElement = document.getElementById(windowId);
            if (modalElement) {
                const modalTitle = modalElement.querySelector('.modal-title');
                if (modalTitle) {
                    modalTitle.textContent = newName;
                }
            }
        }
    });
}

// 保存热点名称到服务器
async function saveHotspotName(hotspotId, name) {
    try {
        const response = await fetch('/save_hotspot_name', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                hotspot_id: hotspotId,
                name: name
            })
        });
        
        if (!response.ok) {
            console.error('保存热点名称失败:', response.status);
        }
    } catch (error) {
        console.error('保存热点名称时发生错误:', error);
    }
}

// 批量删除选中的热点
async function deleteSelectedHotspots() {
    if (selectedHotspots.size === 0) {
        showWarning('没有选中的热点！');
        return;
    }
    
    const count = selectedHotspots.size;
    const confirmed = confirm(`确定要删除 ${count} 个选中的热点吗？`);
    
    if (confirmed) {
        let successCount = 0;
        let failedCount = 0;
        const failedHrefs = [];
        
        // 创建选中热点的副本，避免在删除过程中集合被修改
        const hotspotsToDelete = Array.from(selectedHotspots);
        
        console.log('🔍 批量删除调试信息:');
        console.log('- selectedHotspots原始集合:', selectedHotspots);
        console.log('- selectedHotspots大小:', selectedHotspots.size);
        console.log('- hotspotsToDelete数组:', hotspotsToDelete);
        console.log('- hotspotsToDelete长度:', hotspotsToDelete.length);
        
        try {
            console.log(`开始批量删除 ${hotspotsToDelete.length} 个热点:`, hotspotsToDelete);
            
            // 记录批量删除开始日志
            logger.log('batch_delete', 'hotspot', {
                message: `开始批量删除 ${hotspotsToDelete.length} 个热点`,
                hotspots: hotspotsToDelete,
                level: 'info'
            });
            
            // 逐个删除热点，记录成功和失败的情况
            for (const href of hotspotsToDelete) {
                try {
                    console.log(`正在删除热点: ${href}`);
                    await deleteHotspotByHref(href);
                    successCount++;
                    console.log(`热点 ${href} 删除成功`);
                } catch (error) {
                    console.error(`删除热点 ${href} 失败:`, error);
                    failedCount++;
                    failedHrefs.push(href);
                }
            }
            
            console.log(`批量删除完成: 成功 ${successCount} 个, 失败 ${failedCount} 个`);
            
            // 记录批量删除结果日志
            const resultLevel = failedCount > 0 ? (successCount > 0 ? 'warning' : 'error') : 'info';
            logger.log('batch_delete', 'hotspot', {
                message: `批量删除完成: 成功 ${successCount} 个, 失败 ${failedCount} 个`,
                successCount: successCount,
                failedCount: failedCount,
                failedHrefs: failedHrefs,
                totalRequested: hotspotsToDelete.length,
                level: resultLevel
            });
            
            clearSelection();
            hideContextMenu();
            
            // 根据结果显示不同的消息
            if (failedCount === 0) {
                showSuccess(`成功删除 ${successCount} 个热点！`);
            } else if (successCount === 0) {
                showError(`删除失败！所有 ${failedCount} 个热点都无法删除。`);
            } else {
                showWarning(`部分删除成功：${successCount} 个成功，${failedCount} 个失败。\n失败的热点：${failedHrefs.join(', ')}`);
            }
            
            // 只要有成功删除的，就标记数据已更改
            if (successCount > 0 && dataManager) {
                dataManager.markDataChanged();
            }
        } catch (error) {
            console.error('批量删除热点过程中发生意外错误:', error);
            console.error('错误堆栈:', error.stack);
            
            // 提供更详细的错误信息
            let errorMessage = '批量删除热点时发生意外错误！\n\n';
            errorMessage += `错误详情: ${error.message}\n`;
            errorMessage += `已成功删除: ${successCount} 个\n`;
            errorMessage += `删除失败: ${failedCount} 个`;
            
            showError(errorMessage);
        }
    }
}

// 删除单个热点的辅助函数
async function deleteHotspotByHref(href) {
    console.log(`开始删除热点: ${href}`);
    
    // 验证必要的数据结构
    if (!imageData || !imageData.images) {
        const error = new Error('imageData 未初始化或数据结构异常');
        logger.log('delete', 'hotspot', {
            message: `删除热点失败: ${href}`,
            href: href,
            error: error.message,
            level: 'error'
        });
        throw error;
    }
    
    if (!hotspotInfo) {
        const error = new Error('hotspotInfo 未初始化');
        logger.log('delete', 'hotspot', {
            message: `删除热点失败: ${href}`,
            href: href,
            error: error.message,
            level: 'error'
        });
        throw error;
    }
    
    // 记录删除前状态（用于可能的撤销操作）
    const beforeState = {
        href: href,
        hotspotInfo: hotspotInfo[href] ? {...hotspotInfo[href]} : null,
        imageData: null,
        domElements: {
            hotspotArea: document.querySelector(`[data-href="${href}"]`) ? true : false,
            area: document.querySelector(`area[href="${href}"]`) ? true : false
        }
    };
    
    // 查找并保存热点在imageData中的信息
    imageData.images.forEach(image => {
        const hotspot = image.hotspots.find(h => h.href === href);
        if (hotspot) {
            beforeState.imageData = {
                imageId: image.id,
                hotspot: {...hotspot}
            };
        }
    });
    
    // 从DOM中移除热点可视化区域
    const hotspotArea = document.querySelector(`[data-href="${href}"]`);
    if (hotspotArea) {
        hotspotArea.remove();
        console.log(`已移除热点可视化区域: ${href}`);
    } else {
        console.warn(`未找到热点可视化区域: ${href}`);
    }
    
    // 从DOM中移除area元素
    const area = document.querySelector(`area[href="${href}"]`);
    if (area) {
        area.remove();
        console.log(`已移除area元素: ${href}`);
    } else {
        console.warn(`未找到area元素: ${href}`);
    }
    
    // 从imageData中移除
    let hotspotFound = false;
    imageData.images.forEach(image => {
        const originalLength = image.hotspots.length;
        image.hotspots = image.hotspots.filter(hotspot => hotspot.href !== href);
        if (image.hotspots.length < originalLength) {
            hotspotFound = true;
            console.log(`已从imageData中移除热点: ${href}`);
        }
    });
    
    if (!hotspotFound) {
        console.warn(`在imageData中未找到热点: ${href}`);
    }
    
    // 从hotspotInfo中移除
    if (hotspotInfo[href]) {
        delete hotspotInfo[href];
        console.log(`已从hotspotInfo中移除: ${href}`);
    } else {
        console.warn(`在hotspotInfo中未找到: ${href}`);
    }
    
    // 如果服务器在线，同步删除
    if (serverOnline) {
        try {
            // 使用encodeURIComponent确保特殊字符正确编码
            const hrefParam = encodeURIComponent(href);
            const response = await fetch(`/delete-hotspot/${hrefParam}`, {
                method: 'DELETE'
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const result = await response.json();
            if (!result.success) {
                throw new Error(result.message || '服务器删除失败');
            }
            
            console.log(`热点 ${href} 已从服务器删除`);
        } catch (error) {
            console.error(`服务器删除热点 ${href} 失败:`, error);
            
            // 记录服务器删除失败的日志
            logger.log('delete', 'hotspot', {
                message: `服务器删除热点失败: ${href}`,
                href: href,
                error: error.message,
                level: 'error'
            }, beforeState);
            
            // 在批量删除时，我们需要抛出错误以便上层处理
            throw new Error(`服务器删除失败: ${error.message}`);
        }
    }
    
    // 删除成功，记录操作日志
    const afterState = {
        href: href,
        deleted: true,
        timestamp: new Date().toISOString()
    };
    
    logger.log('delete', 'hotspot', {
        message: `成功删除热点: ${href}`,
        href: href,
        level: 'info'
    }, beforeState, afterState);
}

function showConfirm(message, onConfirm, onCancel) {
    showCustomModal('确认', message, 'warning', [
        {
            text: '取消',
            type: 'secondary',
            onclick: () => {
                closeCustomModal();
                if (onCancel) onCancel();
            }
        },
        {
            text: '确定',
            type: 'danger',
            onclick: () => {
                closeCustomModal();
                if (onConfirm) onConfirm();
            }
        }
    ]);
}

// 显示数据信息
async function showDataInfo() {
    try {
        let info = '';
        
        // 本地数据信息
        const localImageCount = imageData.images.length;
        const localHotspotCount = Object.keys(hotspotInfo).length;
        
        info += `📊 本地数据信息：\n`;
        info += `• 图片数量: ${localImageCount}\n`;
        info += `• 热点数量: ${localHotspotCount}\n`;
        info += `• 下一个热点ID: ${nextHotspotId}\n\n`;
        
        // 如果服务器在线，获取服务器数据信息
        if (serverOnline) {
            try {
                const response = await fetch('/get-data-info');
                const result = await response.json();
                
                if (result.success) {
                    info += `🌐 服务器数据信息：\n`;
                    info += `• 文件大小: ${(result.fileSize / 1024).toFixed(1)}KB\n`;
                    info += `• 图片数量: ${result.imageCount}\n`;
                    info += `• 热点数量: ${result.hotspotCount}\n`;
                    info += `• 最后更新: ${result.lastUpdated}\n`;
                    info += `• 文件修改: ${new Date(result.lastModified).toLocaleString()}\n`;
                } else {
                    info += `❌ 服务器数据文件不存在\n`;
                }
            } catch (error) {
                info += `❌ 无法获取服务器数据信息\n`;
            }
        } else {
            info += `❌ 服务器离线，无法获取服务器数据信息\n`;
        }
        
        showInfo(info);
        
    } catch (error) {
        console.error('获取数据信息失败:', error);
        showError('获取数据信息失败！');
    }
}

// 刷新数据
async function refreshData() {
    showConfirm('确定要刷新数据吗？\n\n这将清除浏览器数据并重新从服务器获取最新数据。', async () => {
        console.log('开始刷新数据...');
        
        try {
            // 清除浏览器本地存储的数据
            localStorage.removeItem('map_hotspots_data');
            localStorage.removeItem('map_hotspots_backup');
            console.log('已清除浏览器本地存储数据');
            
            // 清除页面上的所有图片容器
            const containers = document.querySelectorAll('.image-container');
            containers.forEach(container => {
                container.remove();
            });
            console.log('已清除页面上的图片容器');
            
            // 重置全局变量
            imageData = { images: [] };
            hotspotInfo = {};
            nextHotspotId = 1;
            
            // 重新初始化数据管理器
            if (dataManager) {
                // 强制从服务器重新加载数据
                await dataManager.loadFromProjectFile();
                dataManager.syncDataToPage();
                
                // 重新初始化事件监听器
                if (typeof initEventListeners === 'function') {
                    initEventListeners();
                }
                
                // 更新保存状态
                if (dataManager.updateSaveStatus) {
                    dataManager.updateSaveStatus('数据已刷新');
                }
                
                // 获取数据信息用于显示
                const imageCount = imageData.images.length;
                const hotspotCount = Object.keys(hotspotInfo).length;
                
                showSuccess(`数据刷新成功！\n\n已清除浏览器数据并重新获取服务器数据。\n\n📊 当前数据：\n• 图片数量: ${imageCount}\n• 热点数量: ${hotspotCount}`);
            } else {
                showError('数据管理器未初始化！');
            }
        } catch (error) {
            console.error('刷新数据失败:', error);
            showError('刷新数据失败！');
        }
    });
}

// 恢复备份
async function restoreBackup(filename) {
    showConfirm(`确定要恢复备份 "${filename}" 吗？\n\n当前数据将被备份文件覆盖！`, async () => {
        try {
            const response = await fetch(`/restore-backup/${filename}`, {
                method: 'POST'
            });
            const result = await response.json();
            
            if (result.success) {
                showSuccess('备份恢复成功！\n\n页面将重新加载以应用恢复的数据。');
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                showError(`备份恢复失败: ${result.message}`);
            }
        } catch (error) {
            showError('网络错误，无法恢复备份');
        }
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', async function() {
    console.log('页面加载完成，开始初始化...');
    
    // 检查服务器状态
    await checkServerStatus();
    
    // 初始化数据管理器
    dataManager = new DataManager();
    await dataManager.init();
    
    // 事件监听器已经在DataManager.init()中通过syncDataToPage()初始化了
    // 这里只需要确保所有功能正常工作
    console.log('地图热点展示功能已初始化');
    
    // 测试热点区域是否存在
    const areas = document.querySelectorAll('.hotspot-area');
    console.log('找到热点区域数量:', areas.length);
    areas.forEach((area, index) => {
        console.log(`热点区域 ${index + 1}:`, area.getAttribute('data-href'), area.style.left, area.style.top);
    });
    
    // 定期检查服务器状态
    setInterval(checkServerStatus, 30000); // 每30秒检查一次
    
    // 显示欢迎信息
    console.log('🎉 地图热点展示系统已启动！');
    console.log('📊 数据持久化功能已启用');
    console.log('💾 自动保存间隔：30秒');
    console.log('🔧 固定按钮栏已显示');
    console.log('🐍 Python服务器集成已启用');
    console.log('🔄 服务器状态监控已启用');
    console.log('🎉 右上角Toast提示系统已启用');
    
    // 初始化框选功能
    initSelectionEvents();
    
    // 右键菜单事件监听
    document.getElementById('drawHotspot').addEventListener('click', () => {
        startDrawingMode();
        hideContextMenu();
    });
    
    document.getElementById('renameHotspot').addEventListener('click', () => {
        renameSelectedHotspot();
        hideContextMenu();
    });
    
    document.getElementById('deleteSelectedHotspots').addEventListener('click', () => {
        deleteSelectedHotspots();
    });
    
    document.getElementById('cancelSelection').addEventListener('click', () => {
        clearSelection();
        hideContextMenu();
    });
    
    // 显示交互说明
    setTimeout(() => {
        console.log('显示交互说明...');
        showInfo('🎯 地图热点交互说明\n\n📦 默认选择模式：\n• 左键拖动框选热点\n• 右键显示操作菜单\n\n🎨 绘制模式：\n• 右键选择"画热点"进入\n• 画完自动返回选择模式\n\n⌨️ Ctrl连续绘画：\n• 按住Ctrl键连续画热点\n• 松开Ctrl键退出绘画\n\n🔧 调试：控制台输入 testSelectionStyle() 测试选中样式', 6000);
        
    // 添加testSelectionStyle到全局作用域以便在控制台调用
    window.testSelectionStyle = testSelectionStyle;
}, 1000);

// 新增的链接和ID管理函数
function editLink(linkId) {
    if (window.linkStorage && window.linkStorage[linkId]) {
        const link = window.linkStorage[linkId];
        const newUrl = prompt('编辑链接地址:', link.url);
        if (newUrl !== null) {
            window.linkStorage[linkId].url = newUrl;
            showLinkManager(); // 刷新显示
        }
    }
}

function deleteLink(linkId) {
    if (confirm('确定要删除这个链接吗？')) {
        delete window.linkStorage[linkId];
        showLinkManager(); // 刷新显示
    }
}

function deleteTextId(id) {
    if (confirm('确定要删除这个ID标识吗？')) {
        delete window.idStorage[id];
        showLinkManager(); // 刷新显示
    }
}

// 初始化新功能的额外代码
setTimeout(() => {
    // 初始化全局变量
    window.linkStorage = {};
    window.idStorage = {};
    window.currentSelection = null;
    window.currentSelectionRange = null;
    
    // 全局右键菜单控制
    document.addEventListener('contextmenu', function(e) {
        const selection = window.getSelection();
        const selectedText = selection.toString().trim();
        
        // 如果在预览区域内有文本选择，屏蔽系统右键菜单
        const previewContent = document.getElementById('preview-content');
        if (previewContent && previewContent.contains(selection.anchorNode) && selectedText.length > 0) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    });
    
    // 点击空白处隐藏文本选择菜单
    document.addEventListener('click', function(e) {
        const menu = document.getElementById('text-selection-menu');
        const linkManager = document.getElementById('link-manager');
        
        if (menu && !menu.contains(e.target)) {
            hideTextSelectionMenu();
        }
        
        if (linkManager && !linkManager.contains(e.target) && linkManager.style.display === 'block') {
            const clickedElement = e.target;
            // 如果点击的不是"链接管理"按钮，则关闭面板
            if (!clickedElement.textContent.includes('链接管理')) {
                closeLinkManager();
            }
        }
    });
    
    // 处理锚点链接点击
    document.addEventListener('click', function(e) {
        if (e.target.tagName === 'A' && e.target.getAttribute('href') && e.target.getAttribute('href').startsWith('#')) {
            e.preventDefault();
            const href = e.target.getAttribute('href');
            console.log('点击锚点链接:', href);
            handleAnchorClick(href, e.target);
        }
    });
    
    console.log('🎨 增强编辑器功能已启用');
    console.log('📝 Markdown支持：语法高亮、图片、链接');
    console.log('🔗 文本链接功能：选中文字可添加链接和ID');
    console.log('🎯 双击热点打开编辑器');
}, 1500);

// 测试编辑器函数
function testEditor() {
    console.log('🔧 开始测试编辑器功能...');
    
    // 创建一个简单的测试窗口
    const testContent = `
        <div style="padding: 20px;">
            <h3>编辑器测试</h3>
            <textarea id="test-editor" style="
                width: 100%;
                height: 300px;
                background: #272822;
                color: #f8f8f2;
                border: 2px solid #444;
                padding: 15px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 14px;
                resize: vertical;
            " placeholder="请在这里输入测试文字...">测试内容
这是一个测试编辑器

你应该能够：
1. 看到这段文字
2. 编辑这段文字
3. 添加新内容

如果可以编辑，说明编辑器基本功能正常。</textarea>
            <div style="margin-top: 10px;">
                <button onclick="alert('测试按钮工作正常！')" style="padding: 5px 10px; background: #007bff; color: white; border: none; border-radius: 3px;">测试按钮</button>
                <button onclick="debugCurrentWindow()" style="padding: 5px 10px; background: #28a745; color: white; border: none; border-radius: 3px; margin-left: 10px;">🔍 调试当前窗口</button>
                <button onclick="createFullFeatureTest()" style="padding: 5px 10px; background: #007bff; color: white; border: none; border-radius: 3px; margin-left: 10px;">🧪 完整功能测试</button>
            </div>
        </div>
    `;
    
    const windowId = windowManager.createWindow('test-editor', '🔧 编辑器测试', testContent, {
        width: 600,
        height: 500
    });
    
    // 延迟聚焦到测试编辑器
    setTimeout(() => {
        const testEditor = document.getElementById('test-editor');
        if (testEditor) {
            testEditor.focus();
            testEditor.select(); // 选中所有文本
            console.log('✅ 测试编辑器已聚焦和选中');
        } else {
            console.error('❌ 找不到测试编辑器');
        }
    }, 200);
}

// 调试当前窗口的DOM结构
function debugCurrentWindow() {
    console.log('🔍 开始调试当前窗口...');
    
    // 查找最近打开的热点窗口
    const allWindows = document.querySelectorAll('[data-window-id^="hotspot_"]');
    console.log(`找到 ${allWindows.length} 个热点窗口`);
    
    if (allWindows.length > 0) {
        const latestWindow = allWindows[allWindows.length - 1];
        const windowId = latestWindow.getAttribute('data-window-id');
        console.log(`调试窗口: ${windowId}`);
        
        // 检查窗口结构
        const windowContent = latestWindow.querySelector('.window-content');
        const modalBody = latestWindow.querySelector('.modal-body');
        const editorContainer = latestWindow.querySelector('.editor-container');
        const tabContent = latestWindow.querySelector('.tab-content');
        const tabPanes = latestWindow.querySelectorAll('.tab-pane');
        const activePane = latestWindow.querySelector('.tab-pane.active');
        const textarea = latestWindow.querySelector('textarea');
        
        console.log('窗口DOM结构:', {
            windowContent: !!windowContent,
            modalBody: !!modalBody,
            editorContainer: !!editorContainer,
            tabContent: !!tabContent,
            tabPanes: tabPanes.length,
            activePane: !!activePane,
            textarea: !!textarea
        });
        
        if (tabContent) {
            const computedStyle = window.getComputedStyle(tabContent);
            console.log('tab-content样式:', {
                height: computedStyle.height,
                minHeight: computedStyle.minHeight,
                display: computedStyle.display,
                position: computedStyle.position,
                flex: computedStyle.flex
            });
        }
        
        if (activePane) {
            const computedStyle = window.getComputedStyle(activePane);
            console.log('activePane样式:', {
                height: computedStyle.height,
                display: computedStyle.display,
                position: computedStyle.position,
                background: computedStyle.background
            });
        }
        
        if (textarea) {
            const computedStyle = window.getComputedStyle(textarea);
            console.log('textarea样式:', {
                height: computedStyle.height,
                width: computedStyle.width,
                display: computedStyle.display,
                background: computedStyle.background,
                color: computedStyle.color
            });
        }
        
        // 高亮显示元素
        if (activePane) {
            activePane.style.border = '3px solid red';
            setTimeout(() => {
                activePane.style.border = '';
            }, 3000);
        }
        
        alert('调试信息已输出到控制台，红色边框标识了活动的标签页');
    } else {
        alert('没有找到热点窗口，请先双击一个热点');
    }
}

// 简单版本的切换函数
// 更新时间显示
function updateTime() {
    const timeElement = document.getElementById('currentTime');
    if (timeElement) {
        const now = new Date();
        const timeString = now.toLocaleTimeString('zh-CN', { 
            hour12: false, 
            hour: '2-digit', 
            minute: '2-digit'
        });
        timeElement.textContent = timeString;
    }
}

// 每秒更新时间
setInterval(updateTime, 1000);

// 简单的通知系统
function showNotification(message, type = 'info', duration = 3000) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: ${isTopNavBarHidden ? '20px' : '80px'};
        right: 20px;
        background: ${type === 'info' ? 'rgba(0,123,255,0.9)' : 'rgba(40,167,69,0.9)'};
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 30000;
        font-size: 14px;
        max-width: 300px;
        backdrop-filter: blur(10px);
        transform: translateX(100%);
        transition: transform 0.3s ease;
    `;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 动画显示
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, duration);
}

// 鼠标悬停在顶部边缘时自动显示导航栏
let showNavBarTimeout;

document.addEventListener('mousemove', function(e) {
    if (isTopNavBarHidden && e.clientY <= 5) { // 鼠标在顶部5px范围内
        clearTimeout(showNavBarTimeout);
        showNavBarTimeout = setTimeout(() => {
            if (isTopNavBarHidden) {
                const topNavBar = document.getElementById('fixedButtonBar');
                topNavBar.style.transform = 'translateY(0)';
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    if (isTopNavBarHidden) {
                        topNavBar.style.transform = 'translateY(-100%)';
                    }
                }, 3000);
            }
        }, 500); // 延迟500ms显示
    }
});

// 调整底部布局，防止重叠（现在只需要处理任务栏）
function adjustBottomLayout() {
    const windowManager = document.getElementById('windowManager');
    
    if (windowManager) {
        // 确保任务栏贴在底部
        windowManager.style.bottom = '0px';
        console.log('🔧 任务栏位置已调整到底部');
    }
}

// 页面加载时调整布局
window.addEventListener('load', adjustBottomLayout);
window.addEventListener('resize', adjustBottomLayout);

// 创建全功能测试窗口
function createFullFeatureTestWindow() {
    console.log('🚀 创建全面功能测试窗口...');
    
    const testMarkdown = `# 📋 代码块功能完整测试

本测试窗口包含各种代码块，用于验证：
- ✅ **复制功能**：点击"复制"按钮复制代码到剪贴板
- ✅ **折叠功能**：点击"折叠"按钮收起/展开代码
- ✅ **窗口调整**：拖拽边框调整窗口大小
- ✅ **底部按钮固定**：底部按钮始终固定在页面底部

---

## 🔧 JavaScript 示例
\`\`\`javascript
// 这是一个完整的JavaScript函数示例
function calculateFibonacci(n) {
    if (n <= 1) return n;
    
    let prev = 0;
    let curr = 1;
    
    for (let i = 2; i <= n; i++) {
        let temp = curr;
        curr = prev + curr;
        prev = temp;
    }
    
    return curr;
}

// 测试函数
console.log('斐波那契数列前10项:');
for (let i = 0; i < 10; i++) {
    console.log(\`F(\${i}) = \${calculateFibonacci(i)}\`);
}
\`\`\`

## 🐍 Python 示例
\`\`\`python
# Python类和方法示例
class DataProcessor:
    def __init__(self, data):
        self.data = data
        self.processed = False
    
    def process_data(self):
        """处理数据的主要方法"""
        if self.processed:
            print("数据已经处理过了")
            return self.data
        
        # 数据处理逻辑
        processed_data = []
        for item in self.data:
            if isinstance(item, (int, float)):
                processed_data.append(item * 2)
            elif isinstance(item, str):
                processed_data.append(item.upper())
            else:
                processed_data.append(str(item))
        
        self.data = processed_data
        self.processed = True
        print(f"处理完成，共处理了 {len(self.data)} 项数据")
        return self.data

# 使用示例
data = [1, 2, 3, "hello", "world", 4.5]
processor = DataProcessor(data)
result = processor.process_data()
print(f"处理结果: {result}")
\`\`\`

## 🌐 HTML/CSS 示例
\`\`\`html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>响应式卡片布局</title>
    <style>
        .card-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            padding: 20px;
        }
        
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
            transition: transform 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
    </style>
</head>
<body>
    <div class="card-container">
        <div class="card">
            <h3>卡片标题</h3>
            <p>这是卡片内容...</p>
        </div>
    </div>
</body>
</html>
\`\`\`

## 📊 SQL 查询示例
\`\`\`sql
-- 复杂的数据库查询示例
SELECT 
    u.id,
    u.username,
    u.email,
    COUNT(o.id) as order_count,
    SUM(oi.price * oi.quantity) as total_spent,
    AVG(oi.price) as avg_item_price
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
LEFT JOIN order_items oi ON o.id = oi.order_id
WHERE u.created_at >= '2024-01-01'
    AND u.status = 'active'
GROUP BY u.id, u.username, u.email
HAVING COUNT(o.id) > 0
ORDER BY total_spent DESC
LIMIT 10;

-- 创建索引以提高查询性能
CREATE INDEX idx_users_created_status 
ON users (created_at, status);

CREATE INDEX idx_orders_user_id 
ON orders (user_id);
\`\`\`

---

## 🧪 测试说明

1. **复制测试**：点击任意代码块右上角的"复制"按钮，代码应该被复制到剪贴板
2. **折叠测试**：点击"折叠"按钮，代码块应该收起并显示提示文字
3. **窗口调整**：拖拽窗口边框，窗口大小应该平滑调整
4. **底部按钮**：无论窗口如何变化，底部的功能按钮应该始终固定在页面底部

✨ **如果所有功能都正常工作，说明代码块功能已完美实现！**
`;

    const testContent = `
        <div class="modal-body">
            <div class="editor-container">
                <div class="tab-headers">
                    <button class="tab-header" onclick="switchTab(this, 0)">📝 编辑器</button>
                    <button class="tab-header active" onclick="switchTab(this, 1)">👁️ 预览</button>
                </div>
                <div class="tab-content">
                    <div class="tab-pane">
                        <textarea style="width: 100%; height: 500px; background: #272822; color: #f8f8f2; padding: 15px; font-family: 'Consolas', 'Monaco', 'Courier New', monospace; font-size: 14px; border: none; resize: vertical;">${'${testMarkdown}'}</textarea>
                    </div>
                    <div class="tab-pane active">
                        <div id="full-test-preview" class="preview-content" style="height: 500px; overflow-y: auto; text-align: left; padding: 20px; background: white; border-radius: 4px;"></div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const windowId = windowManager.createWindow('full-feature-test', '🧪 代码块功能完整测试', testContent, {
        width: 900,
        height: 700,
        left: 100,
        top: 50
    });
    
    // 延迟渲染markdown内容
    setTimeout(() => {
        const preview = document.getElementById('full-test-preview');
        if (preview) {
            // 配置marked.js (不使用语法高亮，避免错误)
            marked.setOptions({
                breaks: true,
                gfm: true
            });
            
            let html = marked.parse(testMarkdown);
            
            preview.innerHTML = html;
            
            // 为代码块添加基本样式
            const codeBlocks = preview.querySelectorAll('pre');
            codeBlocks.forEach((block, index) => {
                block.style.backgroundColor = '#2d2d2d';
                block.style.color = '#ccc';
                block.style.padding = '1em';
                block.style.borderRadius = '4px';
                block.style.overflow = 'auto';
                block.style.position = 'relative';
                
                if (!block.querySelector('.code-btn-container')) {
                    // 创建按钮容器
                    const btnContainer = document.createElement('div');
                    btnContainer.className = 'code-btn-container';
                    
                    // 创建复制按钮
                    const copyBtn = document.createElement('button');
                    copyBtn.className = 'code-copy-btn';
                    copyBtn.textContent = '复制';
                    copyBtn.title = '复制代码到剪贴板';
                    copyBtn.onclick = function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        const codeElement = block.querySelector('code') || block;
                        const codeText = codeElement ? (codeElement.textContent || codeElement.innerText || '') : '';
                        
                        if (navigator.clipboard && window.isSecureContext) {
                            navigator.clipboard.writeText(codeText).then(() => {
                                const originalText = this.textContent;
                                this.textContent = '已复制';
                                this.classList.add('copied');
                                
                                setTimeout(() => {
                                    this.textContent = originalText;
                                    this.classList.remove('copied');
                                }, 2000);
                                
                                console.log(`代码块 ${index + 1} 已复制到剪贴板`);
                            });
                        } else {
                            // 备用复制方案
                            try {
                                const textArea = document.createElement('textarea');
                                textArea.value = codeText;
                                textArea.style.position = 'fixed';
                                textArea.style.left = '-999999px';
                                document.body.appendChild(textArea);
                                textArea.select();
                                document.execCommand('copy');
                                textArea.remove();
                                
                                const originalText = this.textContent;
                                this.textContent = '已复制';
                                this.classList.add('copied');
                                
                                setTimeout(() => {
                                    this.textContent = originalText;
                                    this.classList.remove('copied');
                                }, 2000);
                                
                                console.log(`代码块 ${index + 1} 已复制（备用方案）`);
                            } catch (err) {
                                console.error('复制失败:', err);
                            }
                        }
                    };
                    
                    // 创建折叠按钮
                    const foldBtn = document.createElement('button');
                    foldBtn.className = 'code-fold-btn';
                    foldBtn.textContent = '折叠';
                    foldBtn.title = '点击折叠/展开代码块';
                    foldBtn.onclick = function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        block.classList.toggle('code-folded');
                        this.textContent = block.classList.contains('code-folded') ? '展开' : '折叠';
                        
                        console.log(`代码块 ${index + 1} ${block.classList.contains('code-folded') ? '已折叠' : '已展开'}`);
                    };
                    
                    // 添加按钮到容器
                    btnContainer.appendChild(copyBtn);
                    btnContainer.appendChild(foldBtn);
                    
                    // 添加按钮容器到代码块
                    block.appendChild(btnContainer);
                    
                    console.log(`为代码块 ${index + 1} 添加了复制和折叠按钮`);
                }
            });
        }
    }, 300);
};

</script>
    <!-- 右上角提示框容器 -->
    <div class="toast-container" id="toastContainer"></div>
    
    <!-- 框选工具 -->
    <div class="selection-box" id="selectionBox"></div>
    
    <!-- 右键菜单 -->
    <div class="context-menu" id="contextMenu">
        <div class="context-menu-item" id="drawHotspot">
            <span>🎨</span>画热点
        </div>
        <div class="context-menu-item" id="renameHotspot">
            <span>✏️</span>重命名热点
        </div>
        <div class="context-menu-item danger" id="deleteSelectedHotspots">
            <span>🗑️</span>删除选中热点
        </div>
        <div class="context-menu-item" id="cancelSelection">
            <span>❌</span>取消选择
        </div>
    </div>

    <!-- 窗口管理器（类似Windows任务栏） -->
    <div class="window-manager" id="windowManager">
        <div class="manager-header">🪟 任务栏</div>
        <div class="window-list" id="windowList"></div>
    </div>

    <!-- 多窗口容器 -->
    <div class="multi-modal" id="multiModal"></div>
</body>
</html>
